在 Spring MVC 里可以通过以下步骤实现文件上传和下载功能。
1. 项目依赖
确保在 pom.xml
中添加必要的依赖,以下是相关依赖的示例:
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
2. 配置文件上传解析器
在 Spring 配置文件(如 applicationContext.xml
)里配置文件上传解析器:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置最大上传文件大小,单位为字节 -->
<property name="maxUploadSize" value="10485760"/>
</bean>
3. 实现文件上传控制器
创建一个控制器类来处理文件上传请求:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
// 获取文件的字节数组
byte[] bytes = file.getBytes();
// 定义文件保存路径
File saveFile = new File("uploads/" + file.getOriginalFilename());
// 将文件写入指定路径
file.transferTo(saveFile);
return "uploadSuccess";
} catch (IOException e) {
e.printStackTrace();
return "uploadError";
}
} else {
return "uploadError";
}
}
}
4. 实现文件下载控制器
创建一个控制器类来处理文件下载请求:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
@Controller
public class FileDownloadController {
@GetMapping("/download/{fileName}")
@ResponseBody
public void downloadFile(@PathVariable String fileName, HttpServletResponse response) {
File file = new File("uploads/" + fileName);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
try (FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5. 创建 HTML 表单
创建一个 HTML 表单用于文件上传:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
总结
- 文件上传:借助
MultipartFile
接收上传的文件,再把文件保存到指定路径。 - 文件下载:依据文件名从指定路径读取文件,然后将文件内容写入响应流。
你可依据自身需求对文件保存路径、文件大小限制等进行调整。