下面我来详细讲解Java实现文件上传到服务器的完整攻略。首先,我们需要了解两种上传文件的方式:使用Servlet API和使用第三方库。
使用Servlet API
使用Servlet API实现文件上传需要依赖于HttpServletRequest和Part对象。具体步骤如下:
1. 在html页面中添加文件上传表单
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
2. 在Servlet中获取上传的文件
// 获取文件
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream inputStream = filePart.getInputStream();
// 将文件上传到服务器
// 此处可以根据需要自定义上传路径和文件名
String uploadPath = "/path/to/upload/dir/" + fileName;
Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
示例
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig // 必须添加该注解
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream inputStream = filePart.getInputStream();
String uploadPath = "/path/to/upload/dir/" + fileName;
Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
response.getWriter().println("文件上传成功!");
}
}
使用第三方库
除了使用Servlet API,还可以使用第三方库来实现文件上传。这里介绍一下常用的两个库:Apache Commons FileUpload和Spring MVC。
Apache Commons FileUpload
Apache Commons FileUpload是一个流行的文件上传库,使用起来非常方便。具体步骤如下:
1. 添加依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2. 在Servlet中解析上传的文件
// 创建文件上传工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 创建文件上传处理器
ServletFileUpload fileUpload = new ServletFileUpload(factory);
// 解析上传的文件
List<FileItem> fileItemList = fileUpload.parseRequest(request);
// 保存文件
for (FileItem fileItem : fileItemList) {
if (!fileItem.isFormField()) {
String fileName = fileItem.getName();
InputStream inputStream = fileItem.getInputStream();
String uploadPath = "/path/to/upload/dir/" + fileName;
Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
}
}
示例
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> fileItemList = fileUpload.parseRequest(request);
for (FileItem fileItem : fileItemList) {
if (!fileItem.isFormField()) {
String fileName = fileItem.getName();
InputStream inputStream = fileItem.getInputStream();
String uploadPath = "/path/to/upload/dir/" + fileName;
Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
}
}
response.getWriter().println("文件上传成功!");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
Spring MVC
Spring MVC是一个流行的Java Web框架,它也提供了文件上传的功能。具体步骤如下:
1. 添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
2. 配置文件上传处理器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/> <!-- 最大文件大小,单位是字节,默认为1MB -->
</bean>
3. 在Controller中处理文件上传
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
String uploadPath = "/path/to/upload/dir/" + fileName;
Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
return "上传成功!";
}
示例
@Controller
public class FileUploadController {
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
String uploadPath = "/path/to/upload/dir/" + fileName;
Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
return "上传成功!";
}
}
至此,Java实现文件上传到服务器的攻略已完整讲解完毕。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java实现文件上传到服务器 - Python技术站