1、建 upload.jsp
<body>
<h1>文件上传</h1><hr>
<form action="${pageContext.request.contextPath }/servlet/UploadServlet" method="POST" enctype="multipart/form-data">
描述信息1:<input type="text" name="description1"/>
描述信息2:<input type="text" name="description2"/>
<input type="file" name="file1" />
<input type="submit" value="上传"/>
</form>
</body>
2、导包
commons-fileupload.jar
commons-io.jar
3、创建 UploadServlet
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
//1.创建工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(100*1024); //手动设置内存缓冲区 100K
factory.setRepository(new File(this.getServletContext().getRealPath("WEB-INF/temp"))); //手动设置临时文件夹
//2.生产文件上传核心类
ServletFileUpload fileUpload = new ServletFileUpload(factory);
// 检查是否是正确的文件上传表单
if(!fileUpload.isMultipartContent(request)){
throw new RuntimeException("请用正确的表单进行上传!");
}
//3.利用文件上传核心类解析request
List<FileItem> list = fileUpload.parseRequest(request);
//4.遍历所有的FileItem
for(FileItem item : list){
if(item.isFormField()){
//当前是一个普通的字段项
String name = item.getFieldName();
String value = item.getString();
System.out.println(name+":"+value);
}else{
//当前是一个文件上传项
String filename = item.getName();
String uuidName = UUID.randomUUID().toString()+"_"+filename;
int hash = uuidName.hashCode();
String hashStr = Integer.toHexString(hash); //得到String型 hash值
char [] hss = hashStr.toCharArray();
String path = this.getServletContext().getRealPath("WEB-INF/upload");
for(char c : hss){
path+="/"+c;
}
new File(path).mkdirs();
InputStream in = item.getInputStream(); //正文的流
OutputStream out = new FileOutputStream(new File(path,uuidName));
IOUtils.In2Out(in, out);
IOUtils.close(in, out);
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
}