我正在尝试使用jQuery下载文件。问题是我没有关于文件扩展名的参考。我只知道文件名。该文件名是唯一的,因为它与主键共享相同的名称。因此,没有文件是相同的。

这是我使用的jQuery:

$("#tbl_surat_all tbody").on('click','.row_surat', function(e) {
    var no_s    = $(this).find('a').html(); //get the file name
    var b_url   = $('#base_url').val()+"assets/uploads/surat/"; //base_url

    var url     = b_url+no_s; //download_url

    window.location = url; //script_to_download
});


如何仅通过知道文件名来下载文件?

注意:


我没有更改表结构的特权,因此无法更新上传脚本。
该文件是图片,pdf和rars

最佳答案

如果没有发送有效的请求,则无法从服务器打开文件。

如果您不要求带有扩展名的完整文件名,则会收到错误消息。

因此,唯一的解决方法是请求所有可能的文件扩展名。

我们可以尝试包括以下内容:

.jpeg .jpg .png .pdf .rar


然后用请求对其进行迭代。

由于这将打开大量的窗口,因此我们将立即关闭它们,因此它看起来相对平滑。

这是代码:

var url_base='http://127.0.0.1/base_url/file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];

for (i=0;i<ext_arr.length;i++){
    var url=url_base+ext_arr[i];
    window.open(url)
        .addEventListener('load', function(){
            this.close();
    }, false);
}


注意:请注意,为了使其正常工作,请求的文件必须符合相同的原始策略。

编辑:我已经修改了上面的代码,以通过xhttp请求在后台加载资源,然后将其直接输出以供下载。

此方法对于所有类型的文件均应完美运行,而且速度最快!

var url_base='http://127.0.0.1/';
var file_name='file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];


for (i=0;i<ext_arr.length;i++){
    // Define request url
    var url=url_base+file_name+ext_arr[i];
    // Use XMLHttpRequest instead of Jquery $ajax
    var xhttp = new XMLHttpRequest();
    // Set the url as a property
    xhttp['user_filename']=file_name;
    // Bind on ready function
    xhttp.onreadystatechange = function() {
        var a;
        // Check if page has loaded successfully
        if (this.readyState === 4 && this.status === 200) {
            // Trick for making downloadable link
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(this.response);
            // Filename for downloading
            a.download = this.user_filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.parentNode.removeChild(a);
        }
    };
    // Set request url and method
    xhttp.open("GET", url);
    // Set responseType as blob for binary response
    xhttp.responseType = 'blob';
    // Send request
    xhttp.send();
}

10-06 04:17
查看更多