1

I have an upload field and I want to read user input with jquery

My html is this

<input type="hidden" id="MAX_FILE_SIZE" value="1999500" name="MAX_FILE_SIZE">
<input type="file" id="upl-0" name="upl[]">
<input type="file" id="upl-1" name="upl[]">
<input type="file" id="upl-2" name="upl[]">

In my jQuery, I do this

var paths = '';
$('input[type=file]').each(function(){
    paths = paths + $(this).val();
});    
alert(paths);

but I'm getting only the file name, not the full path. When I select C:/folder/file.doc, I get only file.doc. I'm trying to get this path to populate the field again on a failed form attempt without the user having to reselect the files, so I need the full path for this to work. How can I get it?

jblue
  • 4,390
  • 4
  • 46
  • 79
  • 1
    Are you testing it in Firefox? See this: http://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3 – Gelatin Jan 24 '11 at 20:44

1 Answers1

3

Generally, you can't. It would be a huge security issue if you can capture the full path name and (re)populate the value of the upload (file) field with that (or another) file name using JavaScript.

A malicious site can do this without the user knowing it does so and upload (in fact, steal) files from someone's computer.

There may be workarounds for this in several browsers (e.g., using some ActiveXObject), but those are not widely supported (and newer browsers tend to prevent actions like these).

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • Upload fields are such a pain. They make it impossible to have a user-friendly form without doing it entirely with ajax. – jblue Jan 24 '11 at 21:00
  • @jblue: What do you exactly mean by "with ajax"? Generally, you can't access local files within JavaScript, no matter whether you use a 'standard' file input field within a form, or you build one yourself and send the file using an XMLHttpRequest. Using the [File API](http://www.w3.org/TR/FileAPI/), you can do somewhat more, but it is not widely supported, yet. – Marcel Korpel Jan 24 '11 at 21:10
  • Well, that totally sucks then. So if the user submits the form with a required field missing, I always have to ask the user to also re-select the files in addition to correcting the mistake in the missing required field. I'm sure users won't be happy having to re-navigate and re-select all the files they wanted to upload. – jblue Jan 24 '11 at 21:25
  • @jblue: And that's where progressive enhancement pops in: if a user has JavaScript (enabled), it is possible to validate the form *before* it is sent to the server and abort the form (and file) uploading. If JavaScript is disabled (or even circumvented), you'll have to do the validation on the server side and you can adjust the returned form with e.g. a select box and the file name of the file that just got uploaded (as this will happen anyway if the form is sent), so a user isn't required to re-upload the file. – Marcel Korpel Jan 24 '11 at 22:04