问题
Reference: FileReader.readAsDataURL
Considering the following example:
function previewFile(file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
}
reader.readAsDataURL(file);
}
It states:
instanceOfFileReader.readAsDataURL(blob);
blob: The Blob or File from which to read.
How can a local file URL like:
\'file:///C:/path-to/root.png\'
be passed to thereadAsDataURL()
Is
FileReader()
available in a Firefox Addon?
回答1:
This information is outdated as of now, but cannot be deleted.
You can create File instances just by specifying a path when your code is chrome-privileged:
new File("/path/to/file");
File
is a sub-class ofBlob
, so allFile
instances are also validBlob
s. Please note that this requires a platform path, and not a file URL.Yes,
FileReader
is available to addons.
File
and FileReader
are available in all window
s. If you want to use them in a non-window scope (like bootstrap.js
or a code module), you may use nsIDOMFile
/nsIDOMFileReader
.
回答2:
To convert a URL to a Blob for FileReader.readAsDataURL() do this:
var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
var reader = new FileReader();
reader.readAsDataURL(request.response);
reader.onload = function(e){
console.log('DataURL:', e.target.result);
};
};
request.send();
回答3:
Try this I learned this from @nmaier when I was mucking around with converting to ico: Well i dont really understand what array buffer is but it does what we need:
function previewFile(file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result); //this is an ArrayBuffer
}
reader.readAsArrayBuffer(file);
}
notice how i just changed your readAsDataURL
to readAsArrayBuffer
.
Here is the example @nmaier gave me: https://stackoverflow.com/a/24253997/1828637
it has a fiddle
if you want to take this and make a file out of it i would think you would use file-output-stream in the onloadend
回答4:
Expanding on Felix Turner s response, here is how I would use this approach with the fetch
API.
async function createFile(){
let response = await fetch('http://127.0.0.1:8080/test.jpg');
let data = await response.blob();
let metadata = {
type: 'image/jpeg'
};
let file = new File([data], "test.jpg", metadata);
// ... do something with the file or return it
}
createFile();
来源:https://stackoverflow.com/questions/25046301/convert-url-to-file-or-blob-for-filereader-readasdataurl