如何使用JSP/Servlet将文件上传到服务器?

720
如何使用JSP/Servlet将文件上传到服务器?
我尝试了以下方法:
<form action="upload" method="post">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

然而,我只得到了文件名,而没有文件内容。当我在
中添加enctype="multipart/form-data"时,request.getParameter()返回null。
在研究过程中,我偶然发现了Apache Common FileUpload。我尝试了这个方法:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.

很遗憾,该servlet抛出了一个没有明确消息和原因的异常。以下是堆栈跟踪:
SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:637)

也许这篇文章会有所帮助:https://www.baeldung.com/upload-file-servlet - Adam Gerard
1
@Adam:他们从我的答案中抄袭,并在其上添加了一堆广告,试图通过此赚钱。是的,好文章。 - BalusC
1
不,实际上没有复制任何内容。我写了那篇文章的第一稿以及补充代码。核心参考文档可以在这里找到:https://commons.apache.org/proper/commons-fileupload/using.html(并且在文章中有链接和引用)。示例部分是从核心参考文档中摘录的(这就是参考文档的目的——作为参考点),但并非全部(请注意,参考文档没有详细说明)。谢谢! - Adam Gerard
请查看以下链接:https://sandny.com/2017/05/18/servlet-file-upload - ricky
14个回答

-1

使用:

DiskFileUpload upload = new DiskFileUpload();

从这个对象中,您需要获取文件项和字段,然后可以像以下方式一样存储到服务器中:

String loc = "./webapps/prjct name/server folder/" + contentid + extension;
File uploadFile = new File(loc);
item.write(uploadFile);

-1
我能想到的最简单的处理文件和输入控件的方法,而不需要使用大量的库:
  <%
      if (request.getContentType() == null)
          return;
      // For input type=text controls
      String v_Text =
          (new BufferedReader(new InputStreamReader(request.getPart("Text1").getInputStream()))).readLine();

      // For input type=file controls
      InputStream inStr = request.getPart("File1").getInputStream();
      char charArray[] = new char[inStr.available()];
      new InputStreamReader(inStr).read(charArray);
      String contents = new String(charArray);
  %>

<% 是用来做什么的?ASP.NET (C#)?你能解释一下吗?请通过编辑(更改)您的答案来回复,而不是在评论中回复(不要包含“Edit:”,“Update:”或类似的内容 - 答案应该看起来像是今天写的)。 - Peter Mortensen

-2

HTML页面

<html>
    <head>
        <title>File Uploading Form</title>
    </head>

    <body>
        <h3>File Upload:</h3>
        Select a file to upload: <br />
        <form action="UploadServlet" method="post"
              enctype="multipart/form-data">

            <input type="file" name="file" size="50" />
            <br />
            <input type="submit" value="Upload File" />
        </form>
    </body>
</html>

Servlet文件

// Import required java libraries
import java.io.*;
import java.util.*;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {

    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 50 * 1024;
    private int maxMemSize = 4 * 1024;
    private File file;

    public void init() {
        // Get the file location where it would be stored.
        filePath =
               getServletContext().getInitParameter("file-upload");
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
               throws ServletException, java.io.IOException {

        // Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(request);
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
        if (!isMultipart) {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("c:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext())
            {
                FileItem fi = (FileItem)i.next();
                if (!fi.isFormField())
                {
                     // Get the uploaded file parameters
                     String fieldName = fi.getFieldName();
                     String fileName = fi.getName();
                     String contentType = fi.getContentType();
                     boolean isInMemory = fi.isInMemory();
                     long sizeInBytes = fi.getSize();

                     // Write the file
                     if (fileName.lastIndexOf("\\") >= 0) {
                         file = new File(filePath +
                         fileName.substring(fileName.lastIndexOf("\\")));
                     }
                     else {
                         file = new File(filePath +
                         fileName.substring(fileName.lastIndexOf("\\") + 1));
                     }
                     fi.write(file);
                     out.println("Uploaded Filename: " + fileName + "<br>");
                }
            }
            out.println("</body>");
            out.println("</html>");
        }
        catch(Exception ex) {
            System.out.println(ex);
        }
    }

    public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
            throws ServletException, java.io.IOException {

        throw new ServletException("GET method used with " +
                 getClass().getName() + ": POST method required.");
    }
}

文件 web.xml

编译上面的 UploadServlet servlet 并在web.xml文件中创建如下所示的必需条目。

<servlet>
   <servlet-name>UploadServlet</servlet-name>
   <servlet-class>UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>UploadServlet</servlet-name>
   <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

-4
发送多个文件时,我们需要使用 enctype="multipart/form-data"
要发送多个文件,请在 input 标签中使用 multiple="multiple"
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="fileattachments"  multiple="multiple"/>
    <input type="submit" />
</form>

2
我们该如何执行getPart(“fileattachments”)以获取一系列的Parts呢?我认为对于多个文件,getPart不起作用? - CyberMew
“发送多个文件以进行文件”是什么意思(似乎不可理解)?请通过编辑(更改)您的答案来回复,而不是在此处留下评论(不要包含“编辑:”,“更新:”或类似内容 - 问题/答案应该看起来像今天写的)。 - Peter Mortensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接