Chrome: Create file input from blob with Javascrip

2019-01-19 11:03发布

问题:

Well, the files attribute of an input[type=file] is read-only. Therefore I can not write my blob data into this input element.

But if I create a new input file element using Javscript, then possible to insert blob data on creation? I am only interested in solutions working in chrome (extension) - other browsers do not matter.

回答1:

new File() constructor is available at chromium / chrome 38+. See File Constructor Sample , File API.

var date = new Date(),
  filename = "file-" + date.getTime() + ".html";

var generatedFile = new File(
  ["<!DOCTYPE html><html><body>" + filename + "</body></html>"]
  , filename
  , {
  type: "text/html",
  lastModified: date
  }
);

var objUrl = URL.createObjectURL(generatedFile);

console.log(generatedFile, objUrl);

var reader = new FileReader();

reader.addEventListener("load", function(event) {
  console.log(event.target.result)
});

reader.readAsText(generatedFile);