0

这些天我一直在努力解决这个问题,也许你肯定比我知道的更多,你可以帮助我....然后我尝试更好地解释。

我有一个 javascript 文件,它通过库 d3.js 构建 html 代码页并用其他代码替换它,每个部分都有不同的功能......该页面不会收费(Ajax)。在某些时候,我需要允许用户将图像上传到他们的个人资料图片,所以我确保 html 代码诱饵

<input type="file" id="file">

和一个

<input type = "button" onclick = "javaScript: performAjaxSubmit ()">

PerformAjaxSubmit 函数 () 通过 xmlHttpRequest 级别 2 将数据发送到 Java Servlet,据我了解,它不仅可以发送字符串,还可以发送更复杂的内容,例如文件。

功能如下:

function performAjaxSubmit() {
    var sampleFile = document.getElementById("file").files[0];
    var formdata = new FormData();
    formdata.append("sampleFile", sampleFile);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:8080/Prova/Upload", true);
    xhr.send(formdata);
    xhr.onload = function(e) {
        if (this.status == 200) {
            alert(this.responseText);
        }
    };
}

Servlet 中的代码是这样的:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // Check that we have a file upload request
    System.out.println(request.getAttribute("username"));
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
      filePath="C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti";
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath +"/"+ 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
                System.out.println(filePath + 
               fileName.substring(fileName.lastIndexOf("\\")+1));
               file = new File( filePath +"/"+  
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
         }
      }

   }catch(Exception ex) {
       System.out.println(ex);
   }
}

现在(对不起,如果问题有点长)它可以工作,但问题是图像保存在我为我提供命令的路径中:

factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));

那么如何远程保存呢?也就是说,一旦我加载了这样的 Altrevista 的站点,我如何确保它们不是 pià 保存到 C 中,而是保存在项目的文件夹中?

我希望我解释了。我正在使用 Apache Tomcat v7.0。提前致谢!

4

1 回答 1

0

您可以使用ServletContext.getRealPath

此代码返回<context root>/upload(取决于您的部署配置)

request.getSession().getServletContext().getRealPath("/upload")
于 2012-10-11T07:56:09.603 回答