【问题标题】:how to upload a file using commons file upload streaming api如何使用公共文件上传流api上传文件
【发布时间】:2013-03-15 12:05:39
【问题描述】:

我正在关注公共文件上传站点中提供的关于流 API 的示例。我一直在试图弄清楚如何获取上传文件的文件扩展名,如何将文件写入目录,最糟糕的是编写示例 cmets // Process the input stream... 的人在哪里,这让我想知道是不是这样微不足道,我是唯一一个不知道怎么做的人。

【问题讨论】:

  • 这里有大量关于如何执行此操作的信息:link

标签: java jsp


【解决方案1】:

在您的 HTML 文件中使用它:

<form action="UploadController" enctype="multipart/form-data" method="post">  
  <input type="file">  
</form>

UploadController servlet 中,在doPost 方法内:

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List items = upload.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root + "/uploads");
                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }

                File uploadedFile = new File(path + "/" + fileName);
                System.out.println(uploadedFile.getAbsolutePath());
                item.write(uploadedFile);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【讨论】:

  • boolean isMultipart = ServletFileUpload.isMultipartContent(request); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { } else { // Process the input stream ... } }
  • 对于糟糕的代码格式非常抱歉。我在移动设备上。现在你如何处理来自上述 sn-p 的流?
  • 您确定您使用的是流式 API FileItem item = (FileItem) iterator.next(); 吗?我认为应该是FileItemStream item = iterator.next();,这样你就可以使用流媒体了。
  • 必须文件中添加名称参数,如&lt;input type="file" name="file"&gt;,否则文件将无法上传。或者至少它在 Chrome 或 Firefox 上对我不起作用。这一点,并且代码示例使用 Streaming API。
【解决方案2】:

这是一个 Servlet,它可以执行您希望它执行的操作。

package rick;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet; 
@WebServlet("/upload4")
public class UploadServlet4 extends HttpServlet{
  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
         throws ServletException, IOException {
       PrintWriter out = response.getWriter();
       out.print("Request content length is " + request.getContentLength() + "<br/>"); 
       out.print("Request content type is " + request.getHeader("Content-Type") + "<br/>");
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       if(isMultipart){
                  ServletFileUpload upload = new ServletFileUpload();
           try{
               FileItemIterator iter = upload.getItemIterator(request);
               FileItemStream item = null;
               String name = "";
               InputStream stream = null;
               while (iter.hasNext()){
                                     item = iter.next();
                                     name = item.getFieldName();
                                     stream = item.openStream();
                  if(item.isFormField()){out.write("Form field " + name + ": " 
                                           + Streams.asString(stream) + "<br/>");}
                  else {
                      name = item.getName();
                      System.out.println("name==" + name);
                      if(name != null && !"".equals(name)){
                         String fileName = new File(item.getName()).getName();
                         out.write("Client file: " + item.getName() + " <br/>with file name "
                                                    + fileName + " was uploaded.<br/>");
                         File file = new File(getServletContext().getRealPath("/" + fileName));
                         FileOutputStream fos = new FileOutputStream(file);
                         long fileSize = Streams.copy(stream, fos, true);
                         out.write("Size was " + fileSize + " bytes <br/>");
                         out.write("File Path is " + file.getPath() + "<br/>");
                      }
                  }
               }
           } catch(FileUploadException fue) {out.write("fue!!!!!!!!!");}
       } 
  }
} 

【讨论】:

    【解决方案3】:

    所有这些答案的问题在于它没有回答原始问题!!

    正如它所说的“处理输入流”,它确实让您感到困惑下一步该做什么。昨晚我一直在看这个问题,试图从一个答案中找到提示,但什么也没有。我去尝试了其他网站,但没有。

    问题是,我们所做的超出了文件上传的范围,这就是问题所在。

    我们现在正在使用 Java.IO InputStream

      InputStream stream = item.openStream();
    

    现在我们使用那个“流”。

    https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=+writing+a+java+inputstream+to+a+file

    在这里,您可以找到所需的各种答案。它是如此模糊,这很愚蠢,并且看起来您必须对 Commons 做一些额外的事情,但实际上它不是 Commons InputStream 它是 Java.io 的!

    在我们的例子中,我们获取给定的流并通过读取字节数据上传到新文件

    这个网站还有很多可能有用的选项http://www.jedi.be/blog/2009/04/10/java-servlets-and-large-large-file-uploads-enter-apache-fileupload/

    我希望这可以帮助那些对 FileUploading 感到困惑和不熟悉的人,因为我在写这个答案前几分钟才弄清楚这一点。

    这是我将文件保存到根驱动器的代码。

      try {
                System.out.println("sdfk");
    
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
    
    // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload();
    
    // Parse the request
                FileItemIterator iter = upload.getItemIterator(request);
    
    
                while (iter.hasNext())
                {
                    FileItemStream item = iter.next();
                    String name = item.getFieldName();
                    InputStream stream = item.openStream();
    
    
                        System.out.println("File field " + name + " with file name "
                                + item.getName() + " detected.");
                        // Process the input stream
                        File f = new File("/"+item.getName());
    
                     System.out.println(f.getAbsolutePath());
    
                    FileOutputStream fout= new FileOutputStream(f);
                    BufferedOutputStream bout= new BufferedOutputStream (fout);
                    BufferedInputStream bin= new BufferedInputStream(stream);
    
    
                    int byte_;
    
                    while ((byte_=bin.read()) != -1)
                    {
                         bout.write(byte_);
                    }
    
                    bout.close();
                    bin.close();
    
    
                }       
    
            } 
            catch (FileUploadException ex)
            {
                Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            response.sendRedirect("/plans.jsp");
    

    祝你好运!

    【讨论】:

      【解决方案4】:

      有一个很棒的“图书馆”可以为您完成这项工作。它实际上只是一个过滤器的代码示例,它将拦截任何类型为 multipart 的表单帖子,并让您可以访问文件、文件名等......您可以在普通的 servlet 发布方法中处理这些内容。

      http://balusc.blogspot.com/2007/11/multipartfilter.html

      【讨论】:

        【解决方案5】:

        我在这里http://www.javamonamour.org/2015/10/web-application-for-file-upload-with.html 给出了一个完整的工作示例(一个用于 WebLogic 的 Eclipse 项目,但您可以轻松地将它改编为 Tomcat)。

        否则只需 git clone https://github.com/vernetto/WebFileUploaderStreaming。一个完整的工作示例胜过一千个代码 sn-ps。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-18
          • 1970-01-01
          • 2012-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多