3

With the given file path, create a file object. new File(file_path) doesn't work. (WIN/MAC)

When tried creating a new file object using File constructor. There occurs an error.

new File(decodeURI(file_path))

when the above approach is followed File constructor err comes up.

2

3 Answers 3

4

Had the exact same issue today, so I'll provide an answer in TypeScript(3.7.5) based on what worked out for me.

Tips:

  • FileAPI needs a Blob to work with (as others have also stated), it won't work with a file path.

The function:

static async createFile(path: string, name: string, type: string): Promise<File> {
            let response = await fetch(path);
            let data = await response.blob();
            let metadata = {
                type: type
            };
            return new File([data], name, metadata);
}

The call:

await createFile('../assets/images/someInterestingPNGImage.png', 'iAmAFile.png', 'image/png')
        .then((file) => {
            //do something with ur file.
            console.log(file);
         });
Sign up to request clarification or add additional context in comments.

2 Comments

Remark: the file hast to be in the asset-folder (and available in the launched environment - like Angular). Than automatic loading works fine. Thx for the tip which saved my day :-)
@LeO Yup, my bad for not mentioning that part. Tons of kudos for noticing.
1

File API needs a Blob here is work-arround

var GetFileBlobUsingURL = function (url, convertBlob) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.responseType = "blob";
        xhr.addEventListener('load', function() {
            convertBlob(xhr.response);
        });
        xhr.send();
};

var blobToFile = function (blob, name) {
        blob.lastModifiedDate = new Date();
        blob.name = name;
        return blob;
};

var GetFileObjectFromURL = function(filePathOrUrl, convertBlob) {
       GetFileBlobUsingURL(filePathOrUrl, function (blob) {
          convertBlob(blobToFile(blob, 'testFile.jpg'));
       });
};
var FileURL="test/test.jpg"
GetFileObjectFromURL(FileURL, function (fileObject) {
     console.log(fileObject);
});

Comments

1

Here is a simple alternative solution using axios:

const srcToFile = async (src, fileName) => {
    const response = await axios.get(src, {
      responseType: "blob",
    });
    const mimeType = response.headers["content-type"];
    return new File([response.data], fileName, { type: mimeType });
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.