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

喜夏-厌秋 提交于 2019-12-20 12:16:43

问题


I am using the File() constructor for creating file object for uploading a blob file to the server. The following code works fine for Chrome, but fails for Safari and Internet Explorer.

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

The code is breaking at this line and getting this error in console "FileConstructor is not a constructor" (evaluating 'new File([blob],file_name,{type: mimeString})')

Using the FileReader API is an alternative to this but I am not able to fix this issue.


回答1:


I Suggest to use the blob api, I've found the same problem and I solved like that:

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);

It is not a "file", but you can use it like it was.




回答2:


According to web "Can I use" Safari does not support the new File() constructor. See this link http://caniuse.com/#feat=fileapi

So I think you have to either use FileReader or maybe use some of the polyfills listed here https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

Especially this one could be useful for you https://github.com/mailru/FileAPI (I did not use it myself)

Also have a look at this SO answer What to use instead of FileReader for Safari?




回答3:


If you can use ES6 classes:

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);


来源:https://stackoverflow.com/questions/33821631/is-there-an-alternative-for-file-constructor-for-safari-and-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!