同事项目中可能用到基于servlet的上传,给他写了个Demo
1.依赖的jar包
commons-fileupload-1.2.2.jar
commons-io-2.2.jar
servlet-api-2.4.jar
2.项目源码
servlet的实现类FileUpload
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet {
public FileUpload() {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
File uploadPath = new File("D:\\temp");
if(!uploadPath.exists()) {
uploadPath.mkdirs();
}
File tempPathFile = new File("d:\\temp\\buffer\\");
if(!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1048576);
factory.setRepository(tempPathFile);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1000000000000000L);
try {
List e = upload.parseRequest(request);
Iterator i = e.iterator();
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
String fileName = fi.getName();
if(fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
} catch (Exception var13) {
var13.printStackTrace();
}
request.getRequestDispatcher("test.jsp").forward(request, response);
}
}
index.jsp
<html>
<!--<form method="post" enctype="multipart/form-data" action="http://10.13.0.103:8080/messages/dispatch/upload_typed_nonfans_file.json?uid=2028810631&file_type=1&md5=">-->
<form method="post" enctype="multipart/form-data" action="FileUpload">
<input type="text" value="" name="name"/>
<input type="file" name="filedata"/>
<input type="submit" value="submit"/>
</form>
</html>
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FileUpload</servlet-name>
<servlet-class>FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>