使用servlet上传和下载文件

时间:2016-04-16 17:50:01

标签: java servlets download upload

我想编写一个简单的java servlet,它从一个简单的html页面接收文件上传,对文件执行某些操作并将操纵的文件发送给用户。

文件上载事件由服务器端servlet的doPost方法处理。要求是在服务器端上载和处理文件后需要立即显示“另存为...”窗口,用户可以将生成的文件保存到他/她的计算机。

文件上传由doPost处理,文件下载由servlet的doGet方法处理。是否有可能以某种方式将这两个事件捆绑在一起?

我可以接收字节内容作为文件上传事件的响应吗?我上传带有ajax帖子的文件,我可以将内容发送回浏览器,我可以在客户端显示此消息。

是否有可能编写一个聪明的java脚本代码,它接收二进制内容作为post请求的响应,并强制Web浏览器弹出“另存为...”窗口以将接收的字节保存到文件中?

另一种解决方案可能是

  1. 使用ajax上传文件
  2. 在服务器端,新生成的内容将保存到文件中的临时目录
  3. 服务器上文件的id或路径作为响应发送回客户端
  4. client(java script)接收生成文件的id并立即向文件下载servlet发出新的GET请求
  5. 文件下载servlet接收文件的id / path并从temp文件夹中读取它并将i bact发送到客户端Web浏览器。
  6. 此方案的最佳做法是什么?

1 个答案:

答案 0 :(得分:-1)

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();
    }
  }

}

在服务器上上传文件的代码。