基于Hutools图片上传下载

1.pom依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.0</version>
        </dependency>

2.上传

@Component
@Slf4j
public class FileUtils {
    private static final int MAX_POST_SIZE = 10 * 1024 * 1024;
    @Value("${file.preview.port}")
    private String filePreviewPort;
    @Value("${ng.address}")
    private String ngAddress;
    @Value("${upload.path}")
    private String uploadPath;

    public String getUrlPreFix() {
        return ngAddress + ":" + filePreviewPort + File.separator;
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String uploadOne(MultipartFile multipartFile) throws IOException {
        // 参数检验
        if (multipartFile == null) {
            throw new ParamException("文件不能为空");
        }
        // 文件限制10M
        long size = multipartFile.getSize();
        if (size > MAX_POST_SIZE) {
            throw new ParamException("length exceeds limit of 10M");
        }
        String folder = uploadPath + File.separator;
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + multipartFile.getOriginalFilename();
        String path = folder + fileName;
        File file = new File(path);
        if (FileUtil.exist(file)) {
            throw new ParamException("文件已存在");
        }
        File file1 = FileUtil.writeBytes(multipartFile.getBytes(), path);
        if (file1.length() < 0) {
            throw new ParamException("文件上传失败");
        }
        return fileName;
    }


}

3.下载

        String path = "url";
        String fileUrl = uploadPath + File.separator + path;
        File file = FileUtil.file(fileUrl);
        if (StringUtils.isEmpty(path) || file == null || !file.exists()) {
            throw new ParamException("文件不存在");
        }
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/force-download");
        // 设置编码,避免文件名中文乱码
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(path.toString().getBytes("gb2312"), "ISO8859-1"));
        outputStream.write(FileUtil.readBytes(file));
        IoUtil.close(outputStream);
  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值