我需要使用blob将图像文件上传到服务器,但是上传后文件的名称始终设置为“ blob”,或者在下载时始终设置为源代码文件+ .jpg的名称。我的代码可以在Chrome上运行,但是我需要它才能在IE10上运行,但不幸的是我不知道如何操作。

我的工作是这样的:

function uploadBlob() {
    var fileName = //insert method to get the original filename of the file uploaded here...

    var blob = dataURItoBlob(dataURL); //this method gets an image, compresses it and returns it as blob

    var blob2 = new Blob([blob], { type: "image/jpeg" });
                      blob2.lastModifiedDate = new Date();
                      blob2.name = fileName;

    return blob2;
}


使用File Constructor,这会容易得多,但是IE和Edge不支持它。该函数需要返回文件或Blob,并使用我当前的代码将其上传到服务器就可以了,只是文件名不正确。我该如何解决?

最佳答案

上载文件时,可以创建一个包含文件名和文件内容(blob)的FormData对象,然后将其发布到服务器,并将它们存储在同一数据表中的不同列中。

当我们下载文件时,我们可以获得文件名和文件内容,然后,从服务器端获取数据之后,您可以参考以下代码来下载文件:

//IE11 and Edge browser support
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
   return navigator.msSaveOrOpenBlob(file.content, file.name);
    }
    else{
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(file.content);
        link.download = file.name;
        document.body.appendChild(link);
        link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
        link.remove();
        window.URL.revokeObjectURL(link.href);
    }


如果使用IE和Edge浏览器,则可以使用msSaveOrOpenBlob或msSaveBlob方法下载文件,对于其他浏览器,我们可以创建html元素并使用download属性下载文件。

10-05 20:33
查看更多