java - 将上传的文件保存在特定位置

标签 java gwt servlets file-upload

我有以下代码处理服务器上的文件上传。但是如何将文件保存到服务器上的特定位置

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import org.apache.commons.fileupload.FileItem;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




/**
 * This is an example of how to use UploadAction class.
 *  
 * This servlet saves all received files in a temporary folder, 
 * and deletes them when the user sends a remove request.
 * 
 * @author Manolo Carrasco Moñino
 *
 */
public class SampleUploadServlet extends UploadAction {

  private static final long serialVersionUID = 1L;

  Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
  /**
   * Maintain a list with received files and their content types. 
   */
  Hashtable<String, File> receivedFiles = new Hashtable<String, File>();

  /**
   * Override executeAction to save the received files in a custom place
   * and delete this items from session.  
   */
  @Override
  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
    String response = "";
    int cont = 0;
    for (FileItem item : sessionFiles) {
      if (false == item.isFormField()) {
        cont++;
        try {
          /// Create a new file based on the remote file name in the client
          // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_");
          // File file =new File("/tmp/" + saveName);

          /// Create a temporary file placed in /tmp (only works in unix)
          // File file = File.createTempFile("upload-", ".bin", new File("/tmp"));

          /// Create a temporary file placed in the default system temp folder
          File file = File.createTempFile("upload-", ".bin");
          item.write(file);

          /// Save a list with the received files
          receivedFiles.put(item.getFieldName(), file);
          receivedContentTypes.put(item.getFieldName(), item.getContentType());

          /// Compose a xml message with the full file information
          response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n";
          response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n";
          response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n";
          response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n";
        } 
        catch (Exception e) 
        {
        }
      }
    }

    /// Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    /// Send information of the received files to the client.
    return "<response>\n" + response + "</response>\n";
  }

  /**
   * Get the content of an uploaded file.
   */
  @Override
  public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String fieldName = request.getParameter(PARAM_SHOW);
    File f = receivedFiles.get(fieldName);
    if (f != null) {
      response.setContentType(receivedContentTypes.get(fieldName));
      FileInputStream is = new FileInputStream(f);
      copyFromInputStreamToOutputStream(is, response.getOutputStream());
    } else {
      renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
   }
  }

  /**
   * Remove a file when the user sends a delete request.
   */
  @Override
  public void removeItem(HttpServletRequest request, String fieldName)  throws UploadActionException {
    File file = receivedFiles.get(fieldName);
    receivedFiles.remove(fieldName);
    receivedContentTypes.remove(fieldName);
    if (file != null) {
      file.delete();
    }
  }

}

最佳答案

你应该使用 File#createTempFile() which takes a directory反而。

File file = File.createTempFile("upload-", ".bin", new File("/path/to/your/uploads"));
item.write(file);

或者如果您确实想之后将临时文件移动到另一个位置,请使用 File#renameTo() .

File destination = new File("/path/to/your/uploads", file.getName());
file.renameTo(destination);

关于java - 将上传的文件保存在特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4345659/

相关文章:

java - 如何使用t24格式发送SOAP请求

java - HMAC解密

java - Heroku 中的 CPU/内存监控(适用于 Java)

java - 我有一个字符串格式的日期 20090422 110126000 yyyymmdd hh24miss 20090422 110126000

java - 当记录超过 1000 时,智能 gwt 网格分组不起作用

javascript - 带有 Ajax 加载内容的无限滚动 Div?

java - 如何从 Vaadin 8 URL 中删除 "#!"?

java - StreamCorruptedException 仅出现在三个盒子中的两个上?

java - Tomcat 会自动维护一个 MySql 连接池吗?

java - 当我混合 JSTL 1.0 和 JSTL 1.1 taglib 声明时,它会在我的某些服务器上导致 ParseException,但不是全部。为什么?