Zakariyya / blog

https://zakariyya.github.io/blog/
6 stars 1 forks source link

文件上传、下载 #56

Open Zakariyya opened 4 years ago

Zakariyya commented 4 years ago

date: 2018-08-17 14:35:35

文件上传

核心代码

/** 
 * 上传文件到服务器--创建一个工具类,直接调用该方法即可
 * @param mulFile:文件流
 * @param uploadPath:文件上传后存储的路径
 * @return
 */
public static File uploadFile(MultipartFile mulFile, String uploadPath) {

  String fileName = mulFile.getOriginalFilename();// 获取文件名(包括后缀名)
  String suffixName = fileName.substring(fileName.lastIndexOf("."));// 获取文件的后缀名
  String infrontName = fileName.substring(0,fileName.lastIndexOf("."));//获取文件的文件名

  String timestamp = new Timestamp(System.currentTimeMillis()).getTime()+"";//当前时间戳
  String filePath = uploadPath + infrontName + "-" + timestamp + suffixName;// 给名字添加时间戳

  /**
   * 文件存储
   */
  File target = new File(filePath);// 创建一个新文件
  if (!target.getParentFile().exists()) {// 检测是否存在目录
    target.getParentFile().mkdirs();// 新建文件夹
  }
  try {
    mulFile.transferTo(target);// 把file文件写入dest
  } catch (IOException e) {
    e.printStackTrace();
  }
  return target;
}

Controller

@RequestMapping(value = "reload", method = RequestMethod.POST)
public String uploadFile(@RequestParam(value = "mulFile", required = false) MultipartFile uploadfile,
        @RequestParam(value = "id", required = true, defaultValue = "") String id) {

    String uploadPath = "d:/file";
    File result = uploadFile(uploadfile,uploadPath);
    return "";
}

请求

{
    "id":11,
    "mulFile":"#@#!%@#*!%$"//文件流
}

文件下载

核心代码

/**
 * 提供文件下载
 * @return 返回结果集
 */
@RequestMapping(value = "/io", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity<InputStreamResource> download(@RequestParam(value = "id") Integer id) throws Exception {

  val filePath = "D:/file/haha1534299140658.csv";

  val file = new FileSystemResource(filePath);
  HttpHeaders headers = new HttpHeaders();
  headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
  headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
  headers.add("Pragma", "no-cache");
  headers.add("Expires", "0");

  try {
    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(file.contentLength())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(file.getInputStream()));
  } catch (IOException e) {
    e.printStackTrace();
    log.info("==== 文件下载出现异常:IOException::位置:HFileController.download/GET  ===");
  }
  return null;
}

创建 MultipartFile 对象 供后端测试

核心代码

创建

String path = "d:/";
File file = new File(path + "haha.csv");
MultipartFile mulFile = new MockMultipartFile(
        "haha4.csv",        //文件名
        "haha2.csv",        //originalName 相当于上传文件在客户机上的文件名
        ContentType.APPLICATION_OCTET_STREAM.toString(),    //文件类型
        new FileInputStream(file)                           //文件流
);