Attach file to input type=“file” with javascript

前端 未结 1 1295
无人及你
无人及你 2021-01-18 18:39

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 JavaScr

相关标签:
1条回答
  • 2021-01-18 19:32

    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.

    0 讨论(0)
提交回复
热议问题