如何通过表单上传文件并让Java将其作为InputStream处理?

时间:2010-12-17 21:34:39

标签: java http streaming inputstream

我有一个Java类,它接受一个I​​nputStream并对进来的数据进行编码。我如何得到一些可以接受用户上传文件的东西,但是把它当作一个流而不把整个东西保存到磁盘上使用FileInputStream?

基本上我正在寻找一些Java中的轻量级Web框架,它只是让我将用户上传的文件作为数据流。

2 个答案:

答案 0 :(得分:4)

如果尚未完成,请安装网络服务器/ servlet容器,如Apache Tomcat

如果您选择Tomcat 6.x,请使用Apache Commons FileUpload将上传的文件作为InputStream。如果选择Tomcat 7.x(Servlet 3.0),则使用HttpServletRequest#getPart()然后Part#getInputStream()InputStream的形式获取上传的文件。

答案 1 :(得分:1)

import org.apache.commons.fileupload.FileItemStream;
 import org.apache.commons.fileupload.FileItemIterator;
 import org.apache.commons.fileupload.servlet.ServletFileUpload;

 import java.io.InputStream;
 import java.io.IOException;
 import java.util.logging.Logger;

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

 public class FileUpload extends HttpServlet {
   private static final Logger log =
       Logger.getLogger(FileUpload.class.getName());

   public void doPost(HttpServletRequest req, HttpServletResponse res)
       throws ServletException, IOException {
     try {
       ServletFileUpload upload = new ServletFileUpload();
       res.setContentType("text/plain");

       FileItemIterator iterator = upload.getItemIterator(req);
       while (iterator.hasNext()) {
         FileItemStream item = iterator.next();
         InputStream stream = item.openStream();

         if (item.isFormField()) {
           log.warning("Got a form field: " + item.getFieldName());
         } else {
           log.warning("Got an uploaded file: " + item.getFieldName() +
                       ", name = " + item.getName());

           // You now have the filename (item.getName() and the
           // contents (which you can read from stream).  Here we just
           // print them back out to the servlet output stream, but you
           // will probably want to do something more interesting (for
           // example, wrap them in a Blob and commit them to the
           // datastore).
           int len;
           byte[] buffer = new byte[8192];
           while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
             res.getOutputStream().write(buffer, 0, len);
           }
         }
       }
     } catch (Exception ex) {
       throw new ServletException(ex);
     }
   }
 }

该示例摘自Google App Engine文档,因为GAE也不允许应用程序在磁盘上写入文件。可以找到原始示例here