Springboot MultipartFile文件上传与下载

yml文件配置是否可以上传及上传附件大小

  servlet:
    multipart:
      # 允许文件上传
      enabled: true
      # 单个文件大小
      max-file-size: 20MB
      # 设置总上传的文件大小
      max-request-size: 50MB
/**
     * @param files
     * @param request
     * @Description 上传文件
     * @Throws
     * @Return java.util.List
     * @Date 2023-08-02 12:11:02
     * @Author WangKun
     */
    @PostMapping("/upload")
    public List upload(@RequestParam("uploadFiles") MultipartFile[] files, HttpServletRequest request) {
        List list = new ArrayList<>();
        for (MultipartFile file : files) {  //循环保存文件
            JSONObject result = new JSONObject();
            String msg = "";
            //判断上传文件格式
            String fileType = file.getContentType();
            // 要上传的目标文件存放的绝对路径
            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "imags";
            //文件名
            String fileOldName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileOldName) && StringUtils.isNotEmpty(fileOldName)
              && StringUtils.isNotBlank(fileType) && StringUtils.isNotEmpty(fileType)
            ) {
                //获取文件后缀名
                String suffixName = fileOldName.substring(fileOldName.lastIndexOf("."));
                //重新生成文件名
                String fileNewName = UUID.randomUUID() + suffixName;
                // 上传
                if (FileUtils.upload(file, path, fileNewName)) {
                    // 保存数据库信息
                    String id = addAnnex(fileNewName, fileOldName, path, fileType, file.getSize());
                    if (StringUtils.isNotBlank(id) && StringUtils.isNotEmpty(id)) {
                        result.put("fileName", fileNewName);
                        result.put("id", id);
                        msg = "文件上传成功";
                    }
                } else {
                    msg = "文件上传失败";
                }
            }else{
                msg = "文件名或文件类型为空";
            }
            result.put("msg", msg);
            list.add(result);
        }
        return list;
    }

文件上传到了:\target\classes\imags中

Springboot MultipartFile文件上传与下载_第1张图片

 下载:

 /**
     * @param id
     * @param response
     * @Description 文件下载
     * @Throws
     * @Return java.util.List
     * @Date 2023-08-02 13:24:41
     * @Author WangKun
     */
    @GetMapping("/download")
    public void download(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) {
        Annex annex = annexService.selectAnnex(id);
        String fileName = annex.getFileNewName();
        String charsetCode = String.valueOf(StandardCharsets.UTF_8);
        try {
            File file = new File(annex.getFilePath() + File.separator + fileName);
            //中文乱码解决
            String type = request.getHeader("User-Agent").toLowerCase();
            // 字符编码格式
            if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
                //谷歌或火狐
                fileName = new String(fileName.getBytes(charsetCode), "iso8859-1");
            } else {
                //IE
                fileName = URLEncoder.encode(fileName, charsetCode);
            }
            // 设置响应的头部信息
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            // 设置响应内容的类型
            response.setContentType(FileUtils.fileContentType(fileName) + "; charset=" + charsetCode);
            // 设置响应内容的长度
            response.setContentLength((int) file.length());
            // 输出
            FileUtils.outStream(Files.newInputStream(file.toPath()), response.getOutputStream());
        } catch (Exception e) {
            log.error("文件下载异常{}", e.getMessage());
        }
    }

文件工具类:

/**
 * @Description 文件上传工具
 * @Author WangKun
 * @Date 2023/8/2 10:28
 * @Version
 */
@Slf4j
public class FileUtils {

    /**
     * @param file
     * @param path
     * @param fileName
     * @Description 保存文件
     * @Throws
     * @Return boolean
     * @Date 2023-08-02 12:10:39
     * @Author WangKun
     */
    public static boolean upload(MultipartFile file, String path, String fileName) {
        String realPath = path + "\\" + fileName;
        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException | IOException e) {
            log.error("文件上传{} 异常", e.getMessage(),e);
            e.printStackTrace();
            return false;
        }

    }

    /**
     * @param name
     * @Description 设置响应头部信息
     * @Throws
     * @Return java.lang.String
     * @Date 2023-08-02 13:39:15
     * @Author WangKun
     */
    public static String fileContentType(String name) {
        String result = "";
        String fileType = name.toLowerCase();
        if (fileType.endsWith(".png")) {
            result = "image/png";
        } else if (fileType.endsWith(".gif")) {
            result = "image/gif";
        } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
            result = "image/jpeg";
        } else if (fileType.endsWith(".svg")) {
            result = "image/svg+xml";
        } else if (fileType.endsWith(".doc")) {
            result = "application/msword";
        } else if (fileType.endsWith(".xls")) {
            result = "application/x-excel";
        } else if (fileType.endsWith(".zip")) {
            result = "application/zip";
        } else if (fileType.endsWith(".pdf")) {
            result = "application/pdf";
        } else if (fileType.endsWith(".mpeg")) { //MP3
            result = "audio/mpeg";
        } else if (fileType.endsWith(".mp4")) {
            result = "video/mp4";
        } else if (fileType.endsWith(".plain")) {
            result = "text/plain";
        } else if (fileType.endsWith(".html")) {
            result = "text/html";
        } else if (fileType.endsWith(".json")) {
            result = "application/json";
        } else{
            result = "application/octet-stream";
        }
        return result;
    }


    /**
     * @param is
     * @param os
     * @Description 文件下载输出
     * @Throws
     * @Return void
     * @Date 2023-08-02 13:40:47
     * @Author WangKun
     */
    public static void outStream(InputStream is, OutputStream os) {
        try {
            byte[] buffer = new byte[10240];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
                os.flush();
            }
        } catch (Exception e) {
            log.error("文件下载{} 异常", e.getMessage(),e);
        } finally {
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                log.error("关闭流{} 异常", e.getMessage(),e);
                e.printStackTrace();
            }
        }
    }


}

你可能感兴趣的:(spring,boot,后端,java)