页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="fileup" enctype="multipart/form-data" method="post">
<input type="file" name="file" required="required"/><br />
<input name="remark" required="required"/><br/>
<button type="submit">上传</button>
</form>
</body>
</html>
后台:
/**
* @MultipartConfig 3.0条加 注解MultipartConfig 就可以获取到参数值了
*/
@WebServlet("/fileup")
@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#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
String remark = request.getParameter("remark");
System.out.println("获取到值remark:"+remark);
//3.0可以 获取 文件
Part file = request.getPart("file");
//保存文件到D盘
String dest = "D:\\wwwroot";
// 保存文件到一个上传的目录 file.getSubmittedFileName()
System.out.println("file.getName()-->"+file.getName());
System.out.println("file.getContentType()-->"+file.getContentType());
System.out.println("file.getSize()-->"+file.getSize());
System.out.println("file.getSubmittedFileName()-->"+file.getSubmittedFileName());
System.out.println("file.hashCode()-->"+file.hashCode());
System.out.println("file.toString()-->"+file.toString());
System.out.println("file.getHeaderNames()-->"+file.getHeaderNames());
//C:\Users\Administrator\Desktop\tup.ico 截取 最后一个 \ 后面的文件名
Path target = Paths.get(dest, file.getSubmittedFileName().substring(file.getSubmittedFileName().lastIndexOf(File.separator), file.getSubmittedFileName().length()));
System.out.println("文件保存的目标路径:" + target);
try (InputStream in = file.getInputStream()) {
Files.copy(in, target);
} finally {
// Part对象使用完以后,需要删除掉,否则临时文件可能一直都在硬盘上
file.delete();
}
}
}