基于Hutools图片上传下载

时间:2025-03-26 08:40:36

依赖

        <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("${}")
    private String filePreviewPort;
    @Value("${}")
    private String ngAddress;
    @Value("${}")
    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);