Java Web Application:如何获取所选文件的原始路径?

时间:2013-07-23 10:20:02

标签: java jsp java-ee struts2

我的jsp页面中有两个字段:<s:file>标记和<s:textfield>标记。

我尝试在该文本字段中显示所选文件的本地路径。

但我无法找到检索本地选定文件路径的确切解决方案。

Upload.jsp

<body>
    <s:form action="select" method="post" theme="simple" name="f1" enctype="multipart/form-data">
        <s:file name="upload" id="ff" size="40" onchange="javascript:submitForm();"/><br>
        <s:label value="file path"/>
        <s:textfield name="uploadPath" id="path"/><br>
    </s:form>

    <script type="text/javascript">
        function submitForm(){
            var filepath=document.f1.upload.value;
            alert(filepath);
            document.forms[0].submit();
        }
    </script>

</body>

SelectAction.java(提交表单时将调用方法selectForder()

 import com.opensymphony.xwork2.ActionSupport;
 import java.io.File;
 import javax.servlet.http.HttpServletRequest;
 import org.apache.struts2.ServletActionContext;
 import org.apache.struts2.interceptor.ServletRequestAware;
 public class SelectAction extends ActionSupport implements ServletRequestAware{

  private File upload;
  private String uploadPath;
  private String uploadFileName; 
  private HttpServletRequest servletRequest;


  public void setUpload(File upload) {
    this.upload = upload;
  }

  public void setUploadFileName(String uploadFileName) {
    this.uploadFileName = uploadFileName;
  }

  public String getUploadPath() {
    return uploadPath;
  }

  public void setUploadPath(String uploadPath) {
    this.uploadPath = uploadPath;
  }

  public void setServletRequest(HttpServletRequest servletRequest) {
    this.servletRequest=servletRequest;
  }

  public String selectFolder(){

    //I can't get the local path of the selected file with below codes

    System.out.println("1 "+uploadFileName);
    System.out.println("2 "+upload.getAbsoluteFile().getPath());
    System.out.println("3 "+upload.getAbsolutePath());
    uploadPath=uploadFileName;


    try{
    System.out.println("4 "+servletRequest.getRealPath(upload.getPath()));
    System.out.println("5 "+servletRequest.getRealPath(uploadFileName));
    System.out.println("6   "+servletRequest.getSession().getServletContext().getRealPath("/"));

    System.out.println("7 "+ServletActionContext.getServletContext().getRealPath("/files"));


    System.out.println("8 "+SelectAction.class.getProtectionDomain().getCodeSource());


        }
       catch(Exception e)
      {
        System.out.println(e);
        }
       return SUCCESS;
      }

 }

3 个答案:

答案 0 :(得分:1)

出于安全考虑,这是不可能的,抱歉。

你会在StackOverflow和其他地方找到关于这方面的大量讨论(有时会参考某些浏览器实现此安全功能的'fakepath'症状。

没有太多细节,这个安全功能的推理非常简单;没有网站需要(阅读:能够)找到有关用户文件系统的任何信息。因此,当文件上传到服务器时,只应发送文件数据。

从技术上讲,它可能在一些较旧的浏览器中(例如:我认为是IE6),但在这一点上是一种非常普遍的安全功能,你可能会依赖于这些信息。

答案 1 :(得分:0)

如果您仍需要原始路径,则可以使用Internet Explorer。

IE 8 (因为我已经在IE 8上测试了这个),默认情况下会将文件的完整路径发送给应用程序。

答案 2 :(得分:0)

您可以在servlet中使用ContextPath。