Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach a file to an input with javascript

I have an input to upload files

<input type="file" name="comment[video_file]" id="comment_video_file">

Is it possible to attach a file by JavaScript?

I have tried but it didn't work

    let file = new File([videoBlob], "video.mp4", { type: "video/mp4" });
    let element = document.getElementById("comment_video_file");
    element.append("video", video);

If I console log the element after the append it looks like this

<input type="file" name="comment[video_file]" id="comment_video_file">
  "video"
  "[object File]"
</input>

like image 299
sara lance Avatar asked Jan 20 '26 20:01

sara lance


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://example.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 176
UI_Dev Avatar answered Jan 23 '26 10:01

UI_Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!