旁白不多说了直接上主题了。
1、新建上传文件夹
在eclipse中,在我们前面文章中用到的项目HelloJSP,在webapp目录下新建uploadfiles文件夹,如下所示:
2、修改HelloWorld.jsp文件
<body>
<h1>文件上传</h1>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
3、新建servlet
上面表单action里面新建名为upload的servlet文件,然后修改dopost方法如下:
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class Upload
*/
@WebServlet("/Upload")
@MultipartConfig
public class Upload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Upload() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
// 获取上传的文件
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
String uploadPath = getServletContext().getRealPath("") + File.separator + "uploadfiles";
System.out.println(uploadPath);
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 保存文件到服务器
InputStream inputStream = filePart.getInputStream();
Path filePath = Paths.get(uploadPath, fileName);
Files.copy(inputStream, filePath);
inputStream.close();
// 返回成功信息
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("文件上传成功!");
}
}
注意:记得要添加@MultipartConfig注释,否则上传文件会报错。
@MultipartConfig 是一个Java注解,用于在Java Servlet中配置支持文件上传的功能。它通常与标签的enctype属性值设置为"multipart/form-data"一起使用。
当你在Servlet中使用@MultipartConfig注解时,它告诉容器该Servlet可以接收以多部分(multipart)形式发送的请求。多部分请求通常用于上传文件,因为文件的二进制数据需要以多部分形式进行传输。
4、测试上传
在代码里面可以打印出来上传到的路径,如下:
其实是在eclipse工作空间的,webapps目录下添加了上传的文件。