如何使用JSP / Servlet將文件上傳到服務器? - How to upload files to server using JSP/Servlet?

問題:

How can I upload files to server using JSP/Servlet? 如何使用JSP / Servlet將文件上傳到服務器? I tried this: 我嘗試了這個: html

<form action="upload" method="post">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

However, I only get the file name, not the file content. 可是,我只獲得文件名,而不獲得文件內容。 When I add enctype="multipart/form-data" to the <form> , then request.getParameter() returns null . 當我將enctype="multipart/form-data"<form> ,而後request.getParameter()返回null java

During research I stumbled upon Apache Common FileUpload . 在研究期間,我偶然發現了Apache Common FileUpload I tried this: 我嘗試了這個: apache

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.

Unfortunately, the servlet threw an exception without a clear message and cause. 不幸的是,該servlet拋出了一個異常,沒有明確的消息和緣由。 Here is the stacktrace: 這是堆棧跟蹤: tomcat

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://stackoom.com/question/AAC4/如何使用JSP-Servlet將文件上傳到服務器
參考二: https://oldbug.net/q/AAC4/How-to-upload-files-to-server-using-JSP-Servlet
相關文章
相關標籤/搜索