admin管理员组文章数量:1287637
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 es up.
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 es up.
Share Improve this question asked Apr 10, 2019 at 11:28 GurudevGurudev 531 gold badge1 silver badge7 bronze badges 2-
1
This is not correct syntax as a
File
object constructor doesn't accept a path. It wants a byte array, amongst others: developer.mozilla/en-US/docs/Web/API/File/File – Rory McCrossan Commented Apr 10, 2019 at 11:30 - As above, also check which browser you are using: developer.mozilla/en-US/docs/Web/API/File/… – fdomn-m Commented Apr 10, 2019 at 11:31
3 Answers
Reset to default 3Had 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);
});
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);
});
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 });
};
本文标签: javascriptCreate File object using file pathStack Overflow
版权声明:本文标题:javascript - Create File object using file path - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741317097a2371979.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论