Dynamically set value of a file input [duplicate]

2018-12-31 06:55发布

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:
How to set file input value programatically (i.e.: when drag-dropping files)?

4条回答
何处买醉
2楼-- · 2018-12-31 07:25

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.

查看更多
妖精总统
3楼-- · 2018-12-31 07:35

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

查看更多
浮光初槿花落
4楼-- · 2018-12-31 07:37

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;
查看更多
骚的不知所云
5楼-- · 2018-12-31 07:44

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.

查看更多
登录 后发表回答