Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach file to input type="file" with javascript

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();
});
like image 869
matousc Avatar asked Oct 18 '22 00:10

matousc


1 Answers

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.

like image 191
Justin MacArthur Avatar answered Oct 21 '22 05:10

Justin MacArthur