Dynamically set value of a file input

JavascriptHtmlDomGoogle Gears

Javascript Problem Overview


Is there a way to set the value of a file input (<input type="file" />) or is that all blocked for security? I'm trying to use google gears' openFiles to make a simple multi-uploader.

> Note: > > The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017. > >See the answer in this question for details as well as a demo:
https://stackoverflow.com/q/47515232/584192

Javascript Solutions


Solution 1 - Javascript

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

Solution 2 - Javascript

I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.

Solution 3 - Javascript

I ended up doing something like this for AngularJS in case someone stumbles across this question:

const imageElem = angular.element('#awardImg');

if (imageElem[0].files[0])
    vm.award.imageElem = imageElem;
    vm.award.image = imageElem[0].files[0];

And then:

if (vm.award.imageElem)
    $('#awardImg').replaceWith(vm.award.imageElem);
    delete vm.award.imageElem;

Solution 4 - Javascript

I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex SView Question on Stackoverflow
Solution 1 - JavascriptJoelView Answer on Stackoverflow
Solution 2 - JavascriptRichard - IMPI MEDIAView Answer on Stackoverflow
Solution 3 - JavascriptjstudiosView Answer on Stackoverflow
Solution 4 - JavascriptCESAR SOROView Answer on Stackoverflow