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

后端 未结 4 1736
刺人心
刺人心 2020-12-30 04:05

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 Intern

相关标签:
4条回答
  • 2020-12-30 04:16

    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.

    0 讨论(0)
  • 2020-12-30 04:19

    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?

    0 讨论(0)
  • 2020-12-30 04:25

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

    0 讨论(0)
  • 2020-12-30 04:35

    There is a File ponyfill on npm which works with modern module imports. This makes usage simple but you do need to import it in every module where you use new File().

    import File from '@tanker/file-ponyfill';
    
    const myFile = new File(['somefiledata'], 'example.txt', { type: 'text/plain'});
    
    0 讨论(0)
提交回复
热议问题