依赖的jar包
commons-fileupload-1.4.jar
commons-io-2.6.jar
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传</title>
<base href="http://localhost:8080/book/">
</head>
<body>
<forM action="uploadServlet" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"><br>
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</forM>
</body>
</html>
servlet代码
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决上传文件名中文乱码问题
req.setCharacterEncoding("utf-8");
if (ServletFileUpload.isMultipartContent(req)){
//创建FileItemFactory工厂实现类
FileItemFactory fileItemFactory = new DiskFileItemFactory();
//创建用于解析上传数据的工具类ServletFileUpload
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
try {
List<FileItem> list = servletFileUpload.parseRequest(req);
//循环判断每一个表彰项,是普通类型还是上传的文件
for (FileItem fileItem : list) {
if (fileItem.isFormField()){
//普通表单项
System.out.println("青单项的name属性值:"+fileItem.getFieldName());
//解决乱码问题
System.out.println("表单项的value属性值:"+fileItem.getString("UTF-8"));
}else {
//上传的文件
System.out.println("表单项的name属性值:"+fileItem.getFieldName());
System.out.println("上传的文件名:"+fileItem.getName());
fileItem.write(new File("E:\\"+fileItem.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|