# 文件上传-下载
# 配置文件
spring:
servlet:
multipart:
enabled: true
max-file-size: 10MB
max-request-size: 20MB
# 文件存储路径
file:
upload-dir: ./src/main/resources/static/uploads
# 开启资源映射
上传即时生效,无需重启项目
package com.AssetTrack.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 将 /uploads/** 映射到 resources/static/uploads/ 目录
registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:src/main/resources/static/uploads/");
}
}
# 服务接口
package com.AssetTrack.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class FileService {
@Value("${file.upload-dir}")
private String uploadDir;
public Resource getFileAsResource(String fileName) throws Exception {
Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists() && resource.isReadable()) {
return resource;
} else {
throw new Exception("File not found or not readable: " + fileName);
}
}
public String uploadFile(MultipartFile file) throws IOException {
// 确保目录存在
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 保存文件
String fileName = file.getOriginalFilename();
int lastIndex = fileName.lastIndexOf('.');
String prefix;
String suffix = "";
if (lastIndex > 0) {
prefix = fileName.substring(0, lastIndex);
suffix = fileName.substring(lastIndex);
} else {
prefix = fileName;
}
fileName = prefix + "_" + System.currentTimeMillis() + suffix;
Path filePath = uploadPath.resolve(fileName);
file.transferTo(filePath);
return fileName;
}
}
# 控制器示例
package com.base.controller;
import com.base.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/file")
@CrossOrigin
@Api(tags = "文件操作")
public class FileController {
@Autowired
FileService fileService;
@PostMapping("/upload")
@ApiOperation("上传")
public ResponseEntity<String> uploadFile(
@RequestParam("file") MultipartFile file
) {
try {
// 保存文件
String fileName = fileService.uploadFile(file);
fileService.uploadFile(file);
return ResponseEntity.ok("File uploaded successfully: " + fileName);
} catch (Exception e) {
return ResponseEntity.status(500).body("Failed to upload file: " + e.getMessage());
}
}
@GetMapping("/download/{fileName}")
@ApiOperation("下载")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
try {
Resource resource = fileService.getFileAsResource(fileName);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} catch (Exception e) {
return ResponseEntity.status(404).body(null);
}
}
}