I have a form with a file select field. If the user submits the form, but there is a problem with one of the fields, it would be nice to have the file select field "repopulated" with the previous selection. I'm fairly certain that because of browser security policies this is impossible, but maybe there is a workaround out there that I'm unaware of.
问题:
回答1:
It can't be done from security reasons. If JS or HTML could set the file path, any webpage could create a bunch of invisible file upload boxes and literally leech files from your hard disk. Without you knowing.
EDIT: Actually, Firefox has an option to enable this in about:config. But it is disabled by default and other browsers AFAIK don't have this option, so it is irrelevant.
Also, you might be able to achieve this with Flash - it can create some more advanced upload boxes than plain HTML/JS, but I'm not sure whether it has such limitation or not. You may want to check out SWFUpload.
回答2:
The <input type="file" ... />
fields are essentially untouchable by Javascript and even CSS. Very few of its propreties are readable or writeable, and only certain parts of it are stylable.
At most you could do a javascript:history.go(-1)
and hope the form's still cached, but then you lose the ability to display error messages reliably.
Any ability, in any context, which would let arbitrary data (like the upload file path) to be entered would be subverted, so it's locked down hard.