在Spring Boot中实现文件上传和下载通常涉及到使用Spring MVC的MultipartFile
类来处理文件上传,同时配置一个Controller
来处理上传和下载请求。
详细操作步骤
文件上传步骤:
1.创建上传目录:
在服务器上创建一个目录,用于存储上传的文件。确保这个目录具有足够的权限,以便应用程序可以向其中写入文件。
2.配置文件上传属性:
在application.yml
文件中配置文件上传的属性,包括上传目录的路径、文件大小限制等。
spring:
mvc:
servlet:
multipart:
max-file-size: 20MB # 设置单个文件最大大小为10MB
max-request-size: 200MB # 设置多个文件大小为100MB
也可以在application.properties文件中配置文件上传的属性,包括上传目录的路径、文件大小限制等。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
3.创建
@Controller
public interface pdfToWord extends ParpentInterface {
@PostMapping(value = "/getpdffile", name = "上传pdf", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public PdfToWordRsp getpdffile(HttpServletRequest request,
@RequestParam("file") MultipartFile files) throws InterruptedException, IOException;
@GetMapping(value = "/downloadPaper", name = "下载", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<byte[]> download(HttpServletRequest request)throws InterruptedException, IOException;
}
4.创建service
@Service
public class PdfToWordImp implements pdfToWord {
//上传文件
@Override
public JSONObject getpdffile(HttpServletRequest request, MultipartFile files) throws InterruptedException, IOException {
PdfToWordRsp pdfToWordRsp = new PdfToWordRsp();
String id= "";
String fileName= "";
String openid= "";
try {
id= request.getParameter("id");
// 构建文件名称
fileName= request.getParameter("name");
openid= request.getParameter("openid");
}catch (Exception e){
e.printStackTrace();
pdfToWordRsp.setCode("2");
pdfToWordRsp.setMessage("文件名称获取失败");
return pdfToWordRsp;
}
// 构建上传目录路径
// request.getServletContext().getRealPath("/upload");
String uploadPath ="/usr/app/appdata/openai";
// 如果目录不存在就创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir()