ssm整合 使用纯注解的方式实现文件的上传与下载
时间: 2024-01-10 11:03:57 浏览: 56
要使用纯注解的方式实现文件的上传与下载,可以按照以下步骤进行:
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
```
2. 配置文件上传和下载的路径
在 Spring 的配置文件中添加以下内容:
```xml
<!-- 文件上传和下载的路径 -->
<bean id="fileUploadPath" class="java.lang.String">
<constructor-arg value="/path/to/upload"/>
</bean>
<bean id="fileDownloadPath" class="java.lang.String">
<constructor-arg value="/path/to/download"/>
</bean>
```
3. 实现文件上传的控制器
```java
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private String fileUploadPath;
@Autowired
private String fileDownloadPath;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = fileUploadPath + File.separator + fileName;
File dest = new File(filePath);
file.transferTo(dest);
return "File uploaded successfully.";
}
@GetMapping("/download")
public ResponseEntity<Resource> download(@RequestParam("fileName") String fileName) throws IOException {
String filePath = fileDownloadPath + File.separator + fileName;
File file = new File(filePath);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
ResponseEntity<Resource> responseEntity = ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
return responseEntity;
}
}
```
4. 测试文件上传和下载
使用 Postman 或其他工具测试文件上传和下载的接口。
注意事项:
- 文件上传的接口必须使用 POST 请求,并且参数名必须为 "file"。
- 文件下载的接口必须使用 GET 请求,并且参数名必须为 "fileName"。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)