Springboot提供文件的上传、下载、预览接口

Springboot提供文件的上传、下载、预览接口

文件上传

@PostMapping("/upload/tocheckfile")
public JSONObject upload(@RequestPart("uploadFile") MultipartFile file){

    JSONObject response = new JSONObject();
    try {
        FilesUtils.uploadFile(file, toCheckFileDir);
        response.put("code", 2000);
    } catch (Exception e) {
        e.printStackTrace();
        log.error("上传文件出现异常!");
        response.put("code", 5000);
        response.put("error", "上传文件失败, e"+e.toString());
    }
    return response;
}

public static void uploadFile(MultipartFile file, String filePath) {

    File toFile = new File(filePath + file.getOriginalFilename());

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(toFile);
        IOUtils.copy(file.getInputStream(), fileOutputStream);
        log.info("file:{} upload succ !", file.getOriginalFilename());
    }catch (Exception e){
        e.printStackTrace();
        log.error("file:{} upload failed!", file.getOriginalFilename());
    }finally {
        try {
            fileOutputStream.close();
        }catch (Exception e){
            log.error("关闭fileOutputStream 发生异常,\n e:{}", e);
        }
    }
}

文件下载或者预览

文件下载和预览可以使用相同接口,前端代码做调整即可

@PostMapping("/download")
public ResponseEntity<byte[]> download(@RequestBody JSONObject params){
    try{
        
        String filePath = params.getString("filePath");
        return FilesUtils.download(filePath);
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}
public static ResponseEntity<byte[]> download(String filepath) throws Exception{
    File file = new File(filepath);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentDispositionFormData("attachment",
            new String(file.getName().getBytes(StandardCharsets.UTF_8), "utf-8"));// 部分浏览器需要将"utf-8"改"为ISO8859-1",否则会出现文件名中文乱码
    httpHeaders.add("Access-Control-Expose-Headers", "Content-Disposition");
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    // 获取文件的字符数组
    byte[] content = FileUtils.readFileToByteArray(file);
    return new ResponseEntity<>(content, httpHeaders, HttpStatus.OK);
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值