3

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>

5
  • 1
    The files property on an input is a read only property, as far as I am aware. Commented Jul 30, 2020 at 21:40
  • You can't do this, the input can only contain files selected directly by the user themselves, from the file system on their computer/device. If you need to upload this blob then you can do that with JavaScript, but not via this method Commented Jul 30, 2020 at 21:46
  • So, I can't attach it to the input or the form? How can I do it? Commented Jul 30, 2020 at 21:47
  • "So, I can't attach it to the input or the form? How can I do it?" As previously stated YOU CAN'T. It's a security restriction. The file(s) have to be selected by the user. Commented Jul 30, 2020 at 21:51
  • "How can I do it?" ...usually by sending the data via AJAX within a FormData object. A little bit of your own research would help you discover this, and discover some examples. Commented Jul 31, 2020 at 8:57

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

MDN article on file inputs states:

You can set as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57

I tried setting input.files to a files property from a drag-n-drop files event and it worked. Though I'm not sure if it's possible to do it with a manually created File.

If this won't work, try sending an XMLHttpRequest with FormData with a file Blob, as advised in other answers/comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.