springboot 本地文件上传下载
时间: 2023-03-30 12:00:23 浏览: 108
Spring Boot 提供了很多方便的工具来实现本地文件上传和下载。你可以使用 Spring Boot 的 MultipartFile 类来处理上传的文件,使用 Resource 类来处理下载的文件。具体实现可以参考 Spring Boot 官方文档或者相关的教程。
相关问题
springboot本地文件上传后获取文件路径
在Spring Boot应用中,处理文件上传通常涉及前端将文件发送到服务器,然后后端保存文件并返回文件路径给客户端。以下是简单的步骤:
1. 配置MultipartFile:首先,在Controller层的请求处理器上,你需要声明一个`@RequestParam MultipartFile file`,这是Spring MVC用来接收文件上传的对象。
```java
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
// 文件验证和处理逻辑...
}
```
2. 保存文件:Spring提供了一些内置的方式保存文件,如使用`TemporaryUploadedFile`临时存储,或者直接写入到指定目录。例如,你可以创建一个临时文件目录,然后调用`save()`方法:
```java
@Autowired
private FileSystemResource resource;
try {
String filename = file.getOriginalFilename();
Path filePath = Paths.get("uploads/" + filename);
resource.copy(file.getInputStream(), new FileOutputStream(filePath.toFile()));
return "success" + filePath.toUri(); // 返回文件URI,即路径
} catch (IOException e) {
throw new RuntimeException(e);
}
```
这里假设有一个名为"uploads"的目录用于存放上传文件。
springboot vue 文件上传下载
### Spring Boot 和 Vue 实现文件上传和下载
#### 文件上传
为了实现文件上传的功能,在前端部分可以利用 `Vue` 来构建用户界面并处理用户的交互操作;而后端则由 `Spring Boot` 构建 RESTful API 接口来接收来自客户端发送过来的数据流。
在 `Vue` 中,可以通过 `<input type="file">` 或者更高级别的组件如 `element-ui` 的 Upload 组件来进行文件的选择。当选择了要上传的文件之后,会触发相应的事件处理器函数,在这个函数内部创建一个新的 XMLHttpRequest 对象或者是使用 axios 库发起 POST 请求到指定的服务地址,并携带上所选中的文件作为请求体的一部分[^3]。
对于服务器一侧来说,则是在控制器层定义好映射路径以及对应的 HTTP 方法(通常是 POST),并通过 @RequestParam 注解获取 multipart/form-data 类型的内容即上传来的文件对象。接着调用 service 层的方法保存该文件至本地磁盘或其他存储介质中去完成整个流程[^4]。
```java
// Java (Spring Boot Controller)
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file){
try {
// Save the uploaded file to a specific location or process it as needed.
Files.copy(file.getInputStream(), Paths.get(UPLOAD_DIR, file.getOriginalFilename()));
return new ResponseEntity<>("Successfully Uploaded", HttpStatus.OK);
} catch (IOException e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
```
同时为了避免跨域资源共享(CORS)带来的麻烦可以在全局配置类里边加入如下所示的相关设置:
```java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
```
#### 文件下载
针对文件下载这一需求,同样也是前后端协作的过程。先看下后端怎么做的:同样是编写一个 controller 函数用于响应 GET 请求,不过这次返回的是字节数组形式表示的目标资源数据而不是简单的字符串信息了。另外还需要注意设置正确的 MIME-Type 头部字段以便浏览器能够识别出这是个可被解析成附件的形式从而弹框让用户选择保存位置。
```java
@GetMapping("/download/{fileName:.+}")
protected ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException{
Path path = Paths.get(DOWNLOAD_DIR).resolve(fileName);
Resource resource = new UrlResource(path.toUri());
if(resource.exists() || resource.isReadable()){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));
return new ResponseEntity<>(resource,headers,HttpStatus.OK);
}else{
throw new RuntimeException("FAIL!");
}
}
```
而在前端方面只需要简单地向上述接口发出 get 请求并将接收到的结果以 blob 形式展示给用户即可达成目的。这里给出一段基于 axios 的例子说明如何做到这一点[^5]。
```javascript
axios({
url: '/api/download/filename',
method: 'GET',
responseType: 'blob', // Important
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'filename.ext'); //or any other extension
document.body.appendChild(link);
link.click();
});
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)