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

谁说我不能喝 提交于 2020-08-13 07:05:43

问题:

How can I upload files to server using JSP/Servlet? 如何使用JSP / Servlet将文件上传到服务器? I tried this: 我尝试了这个:

<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

During research I stumbled upon Apache Common FileUpload . 在研究期间,我偶然发现了Apache Common FileUpload I tried this: 我尝试了这个:

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: 这是堆栈跟踪:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!