文件上传下载工具类
文件下载,从服务器的目录上下载Excel模板文件
文件上传,把文件上传到服务器指定目录下,或者把文件上传到FastDFS或者OSS
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.yto.safe.common.enums.FileTypeEnums;
import cn.yto.safe.common.enums.ResponseEnums;
import cn.yto.safe.model.base.JsonResponse;
import cn.yto.safe.model.entity.ExcelFile;
import cn.yto.safe.service.ExcelFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
/**
* <p>
* 工具类方法
* </p>
*
* @author yanyg
* @date 2022/3/31 13:13
*/
@Slf4j
@RestController
@RequestMapping("/tool")
public class ToolController {
@Value("${template.path:/opt/template/}")
private String templatePath;
@Value("${upload.path:/opt/upload/}")
private String uploadPath;
@Resource
private ExcelFileService excelFileService;
/**
* <p>
* 下载Excel模板
* </p>
*/
@GetMapping("/downloadTemplate")
public void downloadTemplate(@RequestParam("fileType") String fileType,
HttpServletResponse response) throws Exception {
if (StrUtil.isBlank(fileType)) {
throw new Exception("文件类型不能为空");
}
String fileName = FileTypeEnums.getDescriptionByCode(fileType);
//获取要下载的文件全路径名
String realPath = templatePath + fileName;
//以流的形式下载文件
InputStream fis = new BufferedInputStream(new FileInputStream(realPath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
//清空response
response.reset();
//设置response响应头
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
}
/**
* <p>
* 文件上传获取文件ID接口
* </p>
*
* @param file
* @return {@link JsonResponse}
**/
@PostMapping("/generateFileId")
public JsonResponse fileTest(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return JsonResponse.fail(ResponseEnums.EXCEPTION_BUSINESS, "文件不能为空");
}
Date date = new Date();
// 取年度
int year = DateUtil.year(date);
//获得月份,从0开始计数
int month = DateUtil.month(date) + 1;
String monthStr = String.valueOf(month);
if (month < 10) {
monthStr = "0" + month;
}
String dirPath = uploadPath + year + File.separator + monthStr;
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
// 创建文件夹(可创建多级)
FileUtils.forceMkdir(dirFile);
}
//文件原名称
String fileName = file.getOriginalFilename();
//文件类型
String type = fileName.substring(fileName.lastIndexOf("."));
// 判断文件是否为 excel 文件
if (".xlsx".equals(type) || ".xls".equals(type)) {
String newFileName = IdUtil.simpleUUID() + fileName;
String newFilePath = dirPath + File.separator + newFileName;
// 文件复制
file.transferTo(new File(newFilePath));
ExcelFile excelFile = new ExcelFile();
excelFile.setFileId(IdUtil.simpleUUID());
excelFile.setFileName(newFileName);
excelFile.setFilePath(newFilePath);
excelFile.setFinishImport(false);
int num = excelFileService.saveExcelFile(excelFile);
log.info("文件ID:{},保存记录成功数:{}", excelFile.getFileId(), num);
return JsonResponse.succcess(excelFile);
}
return JsonResponse.fail(ResponseEnums.EXCEPTION_BUSINESS, "不是Excel类型");
}
}
推荐使用第三方sdk
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
网友评论