Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set input file element with file using HTML5 File API

I am using an input file element to upload file in my JSP page. The user can upload the file by clicking on a button which opens a form with browser's browse button

Now, I want to upload the file by using drag drop feature of HTML5 (as described @ html5 rocks page). I am able to extract the file name using File API. Is there a way to load the input file element with the dropped file using File API? (So that I may use the same behavior to upload file)

like image 375
user760755 Avatar asked May 19 '11 09:05

user760755


People also ask

How do you assign a value to an input type file?

In HTML, we will use the type attribute to take input in a form and when we have to take the file as an input, the file value of the type attribute allows us to define an element for the file uploads.

How do you create an input from a file in HTML?

<input type="file"> <input> elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using form submission, or manipulated using JavaScript code and the File API.


2 Answers

There's no way to set the value of a <input type=file> directly in JS. That action requires user intervention (and a click on a file picker). However, you can use xhr.send(FormData) or xhr.send(File) to send the files. See my response here:

HTML5 File API readAsBinaryString reads files as much larger, different than files on disk

In your drop handler, just pas the FileList obtained from evt.dataTransfer.files to that uploadFiles() helper.

like image 122
ebidel Avatar answered Nov 02 '22 01:11

ebidel


I was able to set the "files" attribute of the input element with the files property of the dataTransfer object.

document.getElementById("insert input file id").files = evt.dataTransfer.files;

I just tried using getelement.value and it errors. Set the files property with the files list.

Happy Programming!

Kremnari

like image 30
Kremnari Avatar answered Nov 02 '22 03:11

Kremnari