1、导入jar包
2、前端代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="comup" enctype="multipart/form-data">
姓名:<input type="text" name="name" />
<br/>
照片:<input type="file" name="photo" value="点击浏览"/>
<input type="submit" name="提交" />
</form>
</body>
</html>
3、后台代码
package cn.yuchao.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/comup")
public class CommonsUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//创建磁盘文件工厂
FileItemFactory fif = new DiskFileItemFactory();
//文件上传处理
ServletFileUpload sf = new ServletFileUpload(fif);
try {
List<FileItem> list = sf.parseRequest(req);
String path = req.getRealPath("/upload");
for(FileItem fil:list) {
if(fil.isFormField()) {
System.out.println(fil.getFieldName()+"-----"+fil.getName()+"-----"+fil.getString("utf-8"));
} else {
//避免文件名覆盖
String f = UUID.randomUUID()+fil.getName().substring(fil.getName().lastIndexOf("."));
fil.write(new File(path,f));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}