Servlet3文件上传
文件上传:MultipartConfig
form的enctype 标签:http://www.w3school.com.cn/tags/att_form_enctype.asp
配合多线程。
jsp代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- enctype="multipart/form-data":不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。 --> <form action="/JSPweb/FileUploadServlet" method="post" enctype="multipart/form-data" > <input type="text" name="text" value="textTest" /> <input type="file" name="fileToUpload" /><br /> <input type="submit" value="上传" /> </form> </body> </html>
servlet代码:
@WebServlet("/FileUploadServlet")
// servlet3新特性,通过添加注释上传文件
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String string = request.getParameter("text");
System.out.println(string);
Part part = request.getPart("fileToUpload");
if (part == null) {
System.out.println(this.toString() + "part is null");
}
String mime = part.getContentType();
String ext = "";
if ("image/jpeg".equals(mime)) {
ext = ".jpg";
} else {
response.getWriter().println("您上传的文件类型不合法");
return;
}
String filleName = UUID.randomUUID().toString();
String path = getServletContext().getRealPath("/upload");
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, filleName + ext);
part.write(file.getPath());
}
}
浙公网安备 33010602011771号