繁体   English   中英

如何使用commons文件上传流式api上传文件

[英]how to upload a file using commons file upload streaming api

我正在关注commons文件上传站点中提供的关于流API的示例。 我不知道如何弄清楚如何获取上传文件的文件扩展名,如何将文件写入目录,最糟糕的部分是编写示例注释的人// Process the input stream...它离开了我想知道这是否是如此微不足道,以至于我是唯一一个不懂得的人。

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

这是一个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!!!!!!!!!");}
       } 
  }
} 

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

正如它所说的“处理输入流”一样,它真的让你感到困惑。 昨晚我试着从一个答案中找到一个提示,但是什么都没有。 我去尝试了其他网站,没有。

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

我们现在正在使用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做一些额外的事情,但实际上它并不是公共的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");

祝好运!

有一个梦幻般的'图书馆'为你做这个。 它实际上只是一个Filter的代码示例,它将拦截任何类型为multipart的表单帖子,并允许您访问文件,文件名等...您可以在正常的servlet post方法中处理它。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM