Attach file to input type=“file” with javascript

2019-07-16 13:30发布

问题:

I need to send file (up to few MB) generated by JavaScript to server. I need to do it with POST (not ajax POST).

How can I add file to input type="file" by JavaScript? According to Pre-Populate HTML form file input it seems that it is not possible due to security reasons. But I create the file in browser, this should not be the security issue.

I can probably paste the file as text to other type of input. But I do not feel that it is correct.

What is solution here? Is there way how to put file from browser to file input? Or is it ok to do it with other input? Is there a way how to pack the file to POST without input element?

The could what I would like to use:

$("#button").click(function(e) {
    $('#file').val(export_pdf());
    $('#form').submit();
});

回答1:

It isn't possible to create a file and attach it to an HTML form input but using the FormData object you could send a generated file to the server as part of a post request.

Pulled from the MDN:

var formData = new FormData();

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

Which should get you the same result of a file generated by JS sent to the server.