文件配置
server:
servlet:
multipart:
enabled: true
file-size-threshold: 2KB
max-file-size: 20MB
max-request-size: 20MB
file:
upload:
fileUrl: /api/file/**
fileType: xls,xlsx,png,jpg
filePath: C:/Users/long/Desktop/upload-file-city/
文件操作工具类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
public class FileUtils {
private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
public static Map<String, String> UploadFile (MultipartFile file, String baseDir, String fileType) throws IOException {
String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
List<String> types = Arrays.asList(fileType.split(","));
List<String> result = types.stream().filter(item -> {
return suffix.equals(item);
}).collect(Collectors.toList());
if (result.size() >= 1) {
String fileDir = UUID.randomUUID() + String.valueOf(System.currentTimeMillis()) + "." + suffix;
File saveFile = new File(baseDir + File.separator + fileDir);
if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); }
file.transferTo(saveFile);
log.info("{} 上传成功", file.getOriginalFilename());
Map<String, String> map = new HashMap<>();
map.put("fileName", file.getOriginalFilename());
map.put("fileUrl", fileDir);
return map;
} else {
log.error("{} 类型错误", file.getOriginalFilename());
throw new IOException(file.getOriginalFilename() + "类型错误");
}
}
public static void downloadFile(String filePath, String fileName, String fileUrl, HttpServletResponse response) throws UnsupportedEncodingException {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
String file = filePath + fileUrl;
try (
FileInputStream fileInputStream = new FileInputStream(new File(file));
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
) {
byte[] buffer = new byte[1024];
OutputStream outputStream = response.getOutputStream();
int i = bufferedInputStream.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bufferedInputStream.read(buffer);
}
log.info("{} 文件下载成功", fileName);
} catch (Exception e) {
e.printStackTrace();
log.error("{} 文件下载失败", fileName);
}
}
}
文件路径映射路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class FileConfig extends WebMvcConfigurationSupport {
@Autowired
private OwnerConfig ownerConfig;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(ownerConfig.getFileUrl())
.addResourceLocations("file:" + ownerConfig.getFilePath());
super.addResourceHandlers(registry);
}
}
文件读取配置类
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "file.upload")
public class OwnerConfig {
private String fileUrl;
private String filePath;
private String fileType;
}
文件Service类
import com.city.cluster.config.OwnerConfig;
import com.city.cluster.entity.FileEntity;
import com.city.cluster.repository.FileRepository;
import com.city.cluster.service.FileService;
import com.city.cluster.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
@Service
public class FileServiceImpl implements FileService {
private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);
@Autowired
private OwnerConfig ownerConfig;
@Autowired
private FileRepository fileRepository;
@Override
public FileEntity uploadFile(MultipartFile file) throws IOException {
Map<String, String> uploadFile = FileUtils.UploadFile(file, ownerConfig.getFilePath(), ownerConfig.getFileType());
FileEntity fileEntity = new FileEntity()
.setFileName(uploadFile.get("fileName"))
.setFileUrl(uploadFile.get("fileUrl"))
.setUserId(UUID.randomUUID().toString().replaceAll("-", ""))
.setCreateTime(new Date(System.currentTimeMillis()))
.setUpdateTime(new Date(System.currentTimeMillis()));
return fileRepository.save(fileEntity);
}
@Override
public FileEntity getOneFileById(String fileId) {
return fileRepository.getOne(fileId);
}
}
控制器
import com.city.cluster.config.OwnerConfig;
import com.city.cluster.entity.FileEntity;
import com.city.cluster.service.FileService;
import com.city.cluster.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
@RestController
@RequestMapping("/api")
public class HomeController {
@Autowired
private FileService fileService;
@Autowired
private OwnerConfig ownerConfig;
@PostMapping("/home")
public Object home(MultipartFile file) throws IOException {
System.out.println(file.getOriginalFilename());
return fileService.uploadFile(file);
}
@GetMapping("/download")
public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response) throws UnsupportedEncodingException {
FileEntity fileEntity = fileService.getOneFileById(fileId);
FileUtils.downloadFile(ownerConfig.getFilePath(), fileEntity.getFileName(), fileEntity.getFileUrl(), response);
}
}
测试
访问资源
如果对大家有帮助,欢迎关注下个人公众号,谢谢,哈哈