java - jsp / Servlet如何上传文件到服务器?

  显示原文与译文双语对照的内容

如何使用 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" 添加到 <form> 时,request.getParameter() 返回 null

在研究过程中,我偶然发现了的通用路径名 。 我试过这个:


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

不幸的是,servlet抛出了一个没有明确消息和原因的异常。 下面是 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)

时间:

你需要的文件要包含在你的libcommon-io.1.4.jar 目录,或者如果你正在使用任何编辑器,如NetBeans也那你需要转到项目属性,然后你只需添加该JAR文件并将在各。

要获取 common.io.jar 文件,只需google或者访问 Apache Tomcat网站,你可以在那里获得该文件的免费下载选项。 但是记住一件事:如果你是 Windows 用户,下载二进制压缩文件。

我在用常用的Servlet为每 Html表单它是否具有附件与否。 这个Servlet返回一个 TreeMap,其中键是jsp名称参数和值,值是用户输入,在固定目录下保存所有的附件,你的choice.Here 连接的目录是我们的自定义接口。 我觉得这可以帮助你


public class ServletCommonfunctions extends HttpServlet implements
 Connections {

 private static final long serialVersionUID = 1L;

 public ServletCommonfunctions() {}

 protected void doPost(HttpServletRequest request,
 HttpServletResponse response) throws ServletException,
 IOException {}

 public SortedMap<String, String> savefilesindirectory(
 HttpServletRequest request, HttpServletResponse response)
 throws IOException {
//Map<String, String> key_values = Collections.synchronizedMap( new
//TreeMap<String, String>());
 SortedMap<String, String> key_values = new TreeMap<String, String>();
 String dist = null, fact = null;
 PrintWriter out = response.getWriter();
 File file;
 String filePath ="E:FSPATH12KL06CS048";
 System.out.println("Directory Created????????????"
 + new File(filePath).mkdir());
 int maxFileSize = 5000 * 1024;
 int maxMemSize = 5000 * 1024;
//Verify the content type
 String contentType = request.getContentType();
 if ((contentType.indexOf("multipart/form-data")> = 0)) {
 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(filePath));
//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.
 @SuppressWarnings("unchecked")
 List<FileItem> fileItems = upload.parseRequest(request);
//Process the uploaded file items
 Iterator<FileItem> i = fileItems.iterator();
 while (i.hasNext()) {
 FileItem fi = (FileItem) i.next();
 if (!fi.isFormField()) {
//Get the uploaded file parameters
 String fileName = fi.getName();
//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);
 } else {
 key_values.put(fi.getFieldName(), fi.getString());
 }
 }
 } catch (Exception ex) {
 System.out.println(ex);
 }
 }
 return key_values;
 }
}

如果你正在使用Geronimo和它的嵌入式 Tomcat,就会出现这个问题。 在这种情况下,经过多次测试commons-io和commons-fileupload之后,这个问题源于一个父类加载器处理 commons-xxx jar 。 这必须被阻止。 崩溃总是发生在:


fileItems = uploader.parseRequest(request);

注意,该列表使用的当前版本的fileItems类型已经更改commons-fileupload需在这些方面 List<FileItem> 而无和以前的版本,它是在一般 List

我将commons-fileupload和commons-io的源代码添加到 Eclipse 项目中,以跟踪实际的错误,最后得到一些见解。 首先,抛出的异常是类型Throwable不是声明的FileIOException甚至异常( 这些不会被捕获) 。 第二,错误消息是 obfuscatory,因为它没有找到类,因为axis2找不到 commons-io 。 我的项目中没有使用 Axis2,但作为标准安装的一部分,它作为一个文件夹存在于Geronimo知识库子目录中。

最后,我发现了 1个地方,它们构成了一个工作的解决方案,成功地解决了我的问题。 你必须在部署计划中隐藏来自父装载器的jar 。 这被放入 geronimo-web.xml,我的完整文件如下所示。


Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
 <dep:environment>
 <dep:moduleId>
 <dep:groupId>DataStar</dep:groupId>
 <dep:artifactId>DataStar</dep:artifactId>
 <dep:version>1.0</dep:version>
 <dep:type>car</dep:type>
 </dep:moduleId>

<!--Don't load commons-io or fileupload from parent classloaders-->
 <dep:hidden-classes>
 <dep:filter>org.apache.commons.io</dep:filter>
 <dep:filter>org.apache.commons.fileupload</dep:filter>
 </dep:hidden-classes>
 <dep:inverse-classloading/> 


 </dep:environment>
 <web:context-root>/DataStar</web:context-root>
</web:web-app>

正在为文件发送多个文件我们必须使用 enctype="multipart/form-data"
在输入标记中发送多个文件使用 multiple="multiple"


<form action="upload" method="post" enctype="multipart/form-data">
 <input type="file" name="fileattachments" multiple="multiple"/>
 <input type="submit"/>
</form>

你可以使用 jsp/servlet. 上传文件


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

另一方面服务器端。 使用下列代码。


 package com.abc..servlet;

import java.io.File;
---------
--------


/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public UploadFileServlet() {
 super();
//TODO Auto-generated constructor stub
 }
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//TODO Auto-generated method stub
 response.sendRedirect("../jsp/ErrorPage.jsp");
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//TODO Auto-generated method stub

 PrintWriter out = response.getWriter();
 HttpSession httpSession = request.getSession();
 String filePathUpload = (String) httpSession.getAttribute("path")!=null? httpSession.getAttribute("path").toString() :"" ;

 String path1 = filePathUpload;
 String filename = null;
 File path = null;
 FileItem item=null;


 boolean isMultipart = ServletFileUpload.isMultipartContent(request);

 if (isMultipart) {
 FileItemFactory factory = new DiskFileItemFactory();
 ServletFileUpload upload = new ServletFileUpload(factory);
 String FieldName ="";
 try {
 List items = upload.parseRequest(request);
 Iterator iterator = items.iterator();
 while (iterator.hasNext()) {
 item = (FileItem) iterator.next();

 if (fieldname.equals("description")) {
 description = item.getString();
 }
 }
 if (!item.isFormField()) {
 filename = item.getName();
 path = new File(path1 + File.separator);
 if (!path.exists()) {
 boolean status = path.mkdirs();
 }
/* START OF CODE FRO PRIVILEDGE*/

 File uploadedFile = new File(path + Filename);//for copy file
 item.write(uploadedFile);
 }
 } else {
 f1 = item.getName();
 }

 }//END OF WHILE 
 response.sendRedirect("welcome.jsp");
 } catch (FileUploadException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 } 
 } 
 }

}


DiskFileUpload upload=new DiskFileUpload();

从这个对象中你必须获取文件项和字段,然后就可以像下面这样存储到服务器


 String loc="./webapps/prjct name/server folder/"+contentid+extension;


 File uploadFile=new File(loc);
 item.write(uploadFile);

...