前言
当我们开发一个项目的时候,总会有需要文件操作的模块,本篇就进行Spring boot的文件上传下载的编写
操作流程
1、引入依赖
<!--文件上传下载依赖-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2、新建FileUtil类
@Slf4j
public class FileUtil {
public static String filePrefix;
public static String uploadFile;
public static String uploadFile(MultipartFile multipartFile) {
if (multipartFile == null) {
return null;
}
String fileName = getUploadFileName(multipartFile.getOriginalFilename());
log.info(multipartFile.getOriginalFilename());
try {
File destFile = new File(FileUtil.uploadFile + File.separator + fileName);
multipartFile.transferTo(destFile);
log.info("文件【" + multipartFile.getOriginalFilename() + "】上传成功");
return fileName;
} catch (IOException e) {
log.error("文件上传异常:" + multipartFile.getOriginalFilename(), e);
return null;
}
}
public static String getUploadFileName(String fileName) {
return new StringBuilder()
.append(DateUtil.format(null, DateUtil.PATTERN_yyyyMMddHHmmssSSS))
.append("_").append(getRandomStrByNum(6))
.append(getExtension(fileName))
.toString();
}
public static String getExtension(String fileName) {
if (StringUtils.isEmpty(fileName)) {
return null;
}
return fileName.substring(fileName.lastIndexOf("."));
}
public static String CHAR_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String getRandomStrByNum(int factor) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < factor; i++) {
int index = random.nextInt(36);
System.out.println("========>:" + index);
char c = CHAR_STR.charAt(index);
System.out.println("========>:" + c);
sb.append(c);
}
return sb.toString();
}
3、新建DateUtil类(当然,你可以选择不建这个类)
public class DateUtil {
private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);
public static final String PATTERN_24_h = "yyyy-MM-dd HH:mm:ss";
public static final String PATTERN_yyyyMMddHHmmss = "yyyyMMddHHmmss";
public static final String PATTERN_yyyyMMddHHmmssSSS = "yyyyMMddHHmmssSSS";
public static final String PATTERN_yyyyMMdd = "yyyyMMdd";
public static final String PATTERN_yyyy_MM_dd = "yyyy-MM-dd";
public static final String PATTERN_hhmmss = "hh:mm:ss";
public static final String PATTERN_MMDD = "MMDD";
public static final int [] QUARTERS = {0,1,1,1,2,2,2,3,3,3,4,4,4};
enum TimeUnits{
YEAR,MONTH,DAY,HOUR,MINUTES,SECOND
}
public static Date local2Date(LocalDateTime localDateTime){
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static Date local2Date(LocalDate localDate){
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date local2Date(LocalTime localTime){
return Date.from(LocalDateTime.of(LocalDate.now(), localTime).atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate date2LocalDate(Date date){
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime date2LocalDateTime(Date date){
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
public static LocalTime date2LocalTime(Date date){
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalTime();
}
public static LocalDateTime plusDate(LocalDateTime localDateTime, ChronoUnit chronoUnit, int count){
localDateTime = localDateTime == null ? LocalDateTime.now() : localDateTime;
switch (chronoUnit){
case YEARS:
return localDateTime.plusYears(count);
case MONTHS:
return localDateTime.plusMonths(count);
case DAYS:
return localDateTime.plusDays(count);
case HOURS:
return localDateTime.plusHours(count);
case MINUTES:
return localDateTime.plusMinutes(count);
case SECONDS:
return localDateTime.plusSeconds(count);
case NANOS:
return localDateTime.plusNanos(count);
default:
return localDateTime.plusYears(count);
}
}
public static LocalDate getQuarterOfFirstDay(int quarter){
switch (quarter){
case 1:
return LocalDate.of(LocalDate.now().getYear(),1,1);
case 2:
return LocalDate.of(LocalDate.now().getYear(),4,1);
case 3:
return LocalDate.of(LocalDate.now().getYear(),7,1);
case 4:
return LocalDate.of(LocalDate.now().getYear(),10,1);
default:
return null;
}
}
public static LocalDate getQuarterOfLastDay(int quarter){
switch (quarter){
case 1:
return LocalDate.of(LocalDate.now().getYear(),3,1).with(TemporalAdjusters.lastDayOfMonth());
case 2:
return LocalDate.of(LocalDate.now().getYear(),6,1).with(TemporalAdjusters.lastDayOfMonth());
case 3:
return LocalDate.of(LocalDate.now().getYear(),9,1).with(TemporalAdjusters.lastDayOfMonth());
case 4:
return LocalDate.of(LocalDate.now().getYear(),12,1).with(TemporalAdjusters.lastDayOfMonth());
default:
return null;
}
}
public static String format(LocalDateTime localDateTime, String pattern){
localDateTime = localDateTime == null ? LocalDateTime.now() : localDateTime;
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
public static String getCurrentTime(String pattern){
return format(null,pattern);
}
public static long bewteenTwoDays(LocalDate startDate, LocalDate endDate){
return ChronoUnit.DAYS.between(startDate, endDate);
}
public static long bewteenTwoTimes(LocalDateTime startDateTime, LocalDateTime endDateTime, ChronoUnit chronoUnit){
switch (chronoUnit){
case YEARS:
return ChronoUnit.YEARS.between(startDateTime, endDateTime);
case MONTHS:
return ChronoUnit.MONTHS.between(startDateTime, endDateTime);
case DAYS:
return ChronoUnit.DAYS.between(startDateTime, endDateTime);
case HOURS:
return ChronoUnit.HOURS.between(startDateTime, endDateTime);
case MINUTES:
return ChronoUnit.MINUTES.between(startDateTime, endDateTime);
case SECONDS:
return ChronoUnit.SECONDS.between(startDateTime, endDateTime);
case NANOS:
return ChronoUnit.NANOS.between(startDateTime, endDateTime);
default:
return 0;
}
}
public static int differentDays(Date date1, Date date2)
{
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int day1= cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if(year1 != year2)
{
int timeDistance = 0 ;
for(int i = year1 ; i < year2 ; i ++)
{
if(i%4==0 && i%100!=0 || i%400==0)
{
timeDistance += 366;
}
else
{
timeDistance += 365;
}
}
return timeDistance + (day2-day1) ;
}
else
{
return day2-day1;
}
}
}
4、在WebMvcConfig类中添加如下代码
@Value("${application.filePrefix}")
public String filePrefix;
@Value("${application.uploadFile}")
public String uploadFile;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
FileUtil.filePrefix = filePrefix;
FileUtil.uploadFile = uploadFile;
registry.addResourceHandler(filePrefix +"/**")
.addResourceLocations("file:"+uploadFile);
}
5、配置yml文件
spring:
# 文件上传下载相关配置
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB
application:
#文件上传前缀
filePrefix: /
#文件上传路径
uploadFile: C:/Users/14193/Desktop/待办事项/Spring boot文件操作/
6、编码controller文件
@Slf4j
@RestController
@RequestMapping("file")
public class FileController {
@Resource
private FileService fileService;
@Resource
private HttpServletRequest request;
@Resource
private SysUserService sysUserService;
@ResponseBody
@RequestMapping("upload")
public ResultJson upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file == null) {
return ResultJson.error("文件上传失败");
}
Map<String, String> r = new HashMap<>();
String filePath = FileUtil.uploadFile(file);
r.put("filePath", filePath);
r.put("fileName", file.getOriginalFilename());
r.put("fileSize", file.getSize() + "");
FileOperation uploadFile = new FileOperation();
uploadFile.setFileName(file.getOriginalFilename());
uploadFile.setUploadTime(LocalDateTime.now());
String token =request.getHeader("token");
Long uid = Long.valueOf(JwtUtil.getAudience(token));
uploadFile.setUserId(uid);
uploadFile.setFilePath(filePath);
fileService.save(uploadFile);
SysUser user=new SysUser();
user.setId(uid);
user.setPhoto(filePath);
sysUserService.saveOrUpdate(user);
return ResultJson.ok("文件上传成功", r);
}
@NoNeedToken
@ResponseBody
@RequestMapping("downloadByFilePath")
public ResponseEntity<byte[]> download(String filePath) throws IOException {
if (StringUtils.isEmpty(filePath)) {
throw new RuntimeException("路径不可为空!");
}
String localPath = FileUtil.uploadFile + filePath;
log.info("**********----------"+localPath);
File file = new File(localPath);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",
new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1"));
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
byte[] content = FileUtils.readFileToByteArray(file);
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
}
测试
上传: 下载:
|