<input type=‘file’> for IE gives full path,

2019-01-07 15:44发布

问题:

When perform uploading from IE browser, that my backend(org.apache.commons.fileupload) gets full file path.

For other non-IE browsers it gets filename and it's OK because of security.

How to get filename only from input for IE?

Is it possible to do on UI, because I think it's not very graceful to edit apache lib.

Maybe , some parameter exists for input field?

I can do it on server, but interested in UI approach.

回答1:

The point of the file input is to provide a file. Names that come with it are "whatever the browser vendor feels like using", they aren't guaranteed to have anything to do with the file name on the file system at all.

You can't change what the browser sends.

If you are going to make use of the name sent by the browser, then you need to make sure it is valid for whatever you are going to do with it (e.g. make sure it only includes characters that are allowed in filenames on your filesystem). This makes it something that must be handled on the server (just like any other client supplied data).



回答2:

There is also an IE option under:

  • Internet Options
  • Security tab
  • In "Internet" or "Intranet" click on Custom Level
  • In the Security Settings scroll down until you see “Include local directory path when uploading files to a server” and disable it.
  • Click OK on Internet Options window and refresh.

Alex



回答3:

Try this at server side

Path.GetFileName(file.FileName)



回答4:

There is actually a pretty easy workaround if you are uploading with FormData via Xhr. The FormData.append api allows for you to pass in the filename as the 3rd argument.

const formData = new FormData();
//explicitly setting the file name works in IE 11
formData.append('file', file, file.name);



回答5:

You are interested in a UI approach.
You could add a hidden input-field (or JSON entry) that contains just the bare file-name, populated by javascript.

Using the following cross-browser(including IE)/platform javascript function (taken from my answer here, with full explanation and reference), which gets the filename only:

function extractFilename(s){ 
  // returns string containing everything from the end of the string 
  //   that is not a back/forward slash or an empty string on error
  //   so one can check if return_value===''
  return (typeof s==='string' && (s=s.match(/[^\\\/]+$/)) && s[0]) || '';
} 
<input type="file" onchange="alert(extractFilename(this.value));">



回答6:

Seems like easy to handle this from server side but based on the requirements.

I have tested this in production env and works fine.

String fileName = file.getName();
if (fileName != null) {
    fileName = FilenameUtils.getName(fileName);
}

IE by defaults gives the full path along with the file name, and it causes issue while uploading a file from some shared directory. adding above snippet will resolve the issue and works well in all cases.