dscs63759 2014-03-28 02:58
浏览 51

获取知道名称和可能扩展名的文件

I'm working on a school project. I'm creating a webform that helps the user to edit some entries of a database (let's say I want to edit an entry of the 'books' table).

First, I display a list of books, the user can click on the one he/she wants to edit and all the informations will be retrieved and displayed inside input forms, so that he/she can edit and then submit the updated data.

I'm having one problem. Associated with each book there's a picture that I'd like to display, unfortunately all I can retrieve from the database is the name of the picture file but not the extension. The only extensions allowed are jpeg, gif, jpg and png. What I tried this far is the following function:

function UrlExists(url)
    {   
        var ext = [ ".jpeg", ".jpg", ".png", ".gif" ];
        var http = new XMLHttpRequest();
        var url_ext = '';

        $.each(ext, function(key, value){
                        http.open('HEAD', url+value, false);
                        http.send();
                        if(http.status!=404){
                            url_ext = url+value;
                        }

                    });
        if(url_ext){
            return url_ext;
        }else{
            return "image_path/notfound.jpg";
        }


    }

It's not pretty but it works. The only side-problem are all the warnings on the dev-tool in chrome. I don't really mind but I feel like this is bad practice, I'm basically trying to retrieve the file hitting the server with every allowed extension.

This code works because there are no files with the same name, so there cannot be "picture.jpg" AND "picture.png". Is there a good solution to this problem ? I tried using some php inside jquery, with the glob() function, but I couldn't make it work. Something like this:

$('#image_id').attr('src', '<?php echo json_encode(glob("image_path/filename.{jpg,jpeg,png,gif}", GLOB_BRACE)) ?>' );

It's not really doing any php work, I think I'm missing something to make php work inside a jQuery function or maybe it runs when the document is loaded so it wouldn't work. Anyway I'm not even sure this can work. Any help would be much appreciated. Keep in mind I'm no php/jquery expert ;)

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 聚类分析或者python进行数据分析
    • ¥15 逻辑谓词和消解原理的运用
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
    • ¥20 腾讯企业邮箱邮件可以恢复么
    • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
    • ¥15 错误 LNK2001 无法解析的外部符号