Safari 和 IE 的 File() 构造函数是否有替代方案?

Is there an alternative for File() constructor for Safari and IE?

我正在使用 File() 构造函数创建用于将 blob 文件上传到服务器的文件对象。以下代码适用于 Chrome,但不适用于 Safari 和 Internet Explorer。

image_url = new File([blob],file_name,{type: mimeString});

代码在这一行中断并在控制台中出现此错误 "FileConstructor is not a constructor"(正在评估 'new File([blob],file_name,{type: mimeString})')

使用 FileReader API 是替代方法,但我无法解决此问题。

根据网络 "Can I use" Safari 不支持 new File() 构造函数。看到这个linkhttp://caniuse.com/#feat=fileapi

所以我认为你要么使用 FileReader,要么使用这里列出的一些 polyfills https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

特别是这个可能对你有用https://github.com/mailru/FileAPI(我自己没用过)

也看看这个 SO 答案 What to use instead of FileReader for Safari?

我建议使用 blob api,我发现了同样的问题并且我是这样解决的:

var html = <svg>whatever on svg </svg>
var fileName = "myfile.svg";
var blob = new Blob([html], {type: 'image/svg'});
blob.lastModifiedDate = new Date();
// var blobAttrs = {type: "image/svg"};
// var file = new File([html], fileName, blobAttrs);
var formData = new FormData();
formData.append("file",blob,fileName);

它不是 "file",但您可以照原样使用它。

如果你可以使用 ES6 类:

class CustomFile extends Blob
{
    constructor(blobParts, filename, options) {
        super(blobParts, options);
        this.name = filename || "";
        if(options) {
          this.lastModified = options.lastModified;
        }
    }

    lastModified = 0;
    name = "";
}
const blob = new Blob();
const fileObject = new CustomFile([blob],"myfile");

console.log(fileObject);

有一个文件 ponyfill on npm 适用于现代模块导入。这使使用变得简单,但您确实需要在使用 new File().

的每个模块中导入它
import File from '@tanker/file-ponyfill';

const myFile = new File(['somefiledata'], 'example.txt', { type: 'text/plain'});