【知识分享】SpringBoot实现文件上传下载

2023-12-15 00:11:08

在Spring Boot中,可以使用MultipartFile来实现文件上传和下载功能。以下是文件上传和下载的详细过程和代码示例:

1.实现文件上传:

  • 创建一个Controller类,用于处理文件上传请求。

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileController {

? ? @PostMapping("/upload")
? ? public String uploadFile(@RequestParam("file") MultipartFile file) {
? ? ? ? // 获取上传的文件名
? ? ? ? String fileName = file.getOriginalFilename();
? ? ? ??
? ? ? ? // 文件保存路径,根据自己的需求进行修改
? ? ? ? String filePath = "C:/uploads/" + fileName;

? ? ? ? try {
? ? ? ? ? ? // 将文件保存到指定路径
? ? ? ? ? ? file.transferTo(new File(filePath));
? ? ? ? ? ? return "File uploaded successfully!";
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? return "File upload failed.";
? ? ? ? }
? ? }
}

2.实现文件下载:

  • 创建一个Controller类,用于处理文件下载请求。

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class FileController {

? ? @GetMapping("/download")
? ? public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
? ? ? ? // 文件路径,根据实际情况进行修改
? ? ? ? String filePath = "C:/uploads/example.txt";
? ? ? ? File file = new File(filePath);

? ? ? ? // 设置响应头
? ? ? ? HttpHeaders headers = new HttpHeaders();
? ? ? ? headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.txt");

? ? ? ? // 创建文件输入流
? ? ? ? FileInputStream inputStream = new FileInputStream(file);

? ? ? ? // 创建响应实体,并设置内容和响应头
? ? ? ? return ResponseEntity
? ? ? ? ? ? ? ? .ok()
? ? ? ? ? ? ? ? .headers(headers)
? ? ? ? ? ? ? ? .contentType(MediaType.APPLICATION_OCTET_STREAM)
? ? ? ? ? ? ? ? .body(new InputStreamResource(inputStream));
? ? }
}

文章来源:https://blog.csdn.net/lf21qp/article/details/134925571
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。