通用MultipartFile 文件上传下载、前端页面显示、下载在浏览器左下角显示

  • Post author:
  • Post category:其他

@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Value("${upload.filePath}")
    private String filePath;

    @Override
    public Result upload(MultipartFile file) {
    	// 获取文件名 
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String oldName = filename.substring(0, filename.lastIndexOf("."));
        String replace = UUID.randomUUID().toString().replace("-", "");
        String newName = oldName + "_" + replace + suffix;
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = suffix.substring(suffix.indexOf(".") + 1);
        // 拼接新的路径 这里可以换成文件类型dir在前面 然后根据日期format
        String path = filePath +format+File.separator+dir;
		// 判断文件路径不存在创建路径
        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        log.info("文件上传路径:{}",path+File.separator+newName);

        try {
            file.transferTo(Paths.get(path,newName));
        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage());
            e.printStackTrace();
        }
        // 因为 File.separator 在windows上是\\路径分割符号 不便于测试 这里就写死了 
        return Result.success(format+"/"+dir+"/"+newName);
    }

    @Override
    public void download(String path, HttpServletResponse response) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(filePath + path));
            String outFileName = path.substring(path.lastIndexOf(File.separator) + 1);
            ServletOutputStream outputStream = response.getOutputStream();
            // 文件下载的关键就只这两句了
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(outFileName,"UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            log.error("文件下载失败:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

}

然后在说一个坑 你用swagger或者knife4j 下载是不显示的 你要把路径放在浏览器地址栏测试

在这里插入图片描述
这里可能有个问题就是路径要不要截取后端处理。

其他注意事项

配置 swagger 文档文件上传 需要注意 用 @RequestPart , paramType = “form” 这两个,第一个不配置就传不上去,第二个不配置就没有上传文件的那个选择项
在这里插入图片描述

  @ApiOperation(value = "文件上传", notes = "文件上传")
    @ApiImplicitParam(name = "file",value = "单文件上传",required = true,dataType="MultipartFile",
            allowMultiple = true,paramType = "form")
    @PostMapping("/upload")
    public Result upload(@RequestPart("file") MultipartFile file) {
        return commonService.upload(file);
    }

版权声明:本文为yumingyang0212原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。