• Java简单实现图片上传与下载


    1. 懒惰简单开发->上传图片

    1.1 上传 transferTo

    1.1.1 代码

    • 代码如下:
          @PostMapping("/uploadFileTest1")
          @ApiOperation("上传图片1")
          public ViewResultData uploadFileTest1(@RequestPart("upFile") MultipartFile upFile){
              String filePathName = "F:/file/uploadPath" + File.separator + upFile.getOriginalFilename();
              File file = new File(filePathName);
              try {
                  if (!file.getParentFile().exists()) {
                      file.getParentFile().mkdirs();
                  }
                  if (!file.exists()) {
                      file.createNewFile();
                  }
                  upFile.transferTo(file);
                  return new ViewResultData(ReturnCode.SUCCESS_000000,"图片上传成功");
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return new ViewResultData(ReturnCode.SUCCESS_000000,"图片上传失败");
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
    • 演示与效果:
      在这里插入图片描述
      在这里插入图片描述

    1.1.2 transferTo问题

    • 第二次操作报错,如下:
      java.io.IOException: java.io.FileNotFoundException: C:\Users\Administrator\AppData\Local\Temp\tomcat.8993.6340478007086561314\work\Tomcat\localhost\ROOT\upload_aaf3bf6d_b6ba_4888_91ae_ab07ba25701e_00000000.tmp (系统找不到指定的文件。)
      	at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:122)
      
      • 1
      • 2

    在这里插入图片描述

    • 上网搜了一下,问题原因大概是:因为在transferTo后打开了一个新的流然后未关闭造成的
    • 解决可以用:
      ① 用 FileCopyUtils.copy(file1,file2);
      在这里插入图片描述
      ② 用字节流,如下1.2

    1.2 用字节流输出文件

    1.2.1 自己写

    • 代码如下:
      在这里插入图片描述

      /**
           * byte[]类型转File
           * @param bytes
           * @param uploadPath 文件输出目录
           * @param fileName 文件名
           * @return
           */
          public static File bytesToFile(byte[] bytes, String uploadPath, String fileName) {
              BufferedOutputStream bos = null;
              FileOutputStream fos = null;
              File file = null;
              try {
                  file = createNewFile(uploadPath,fileName);
                  fos = new FileOutputStream(file);
                  bos = new BufferedOutputStream(fos);
                  bos.write(bytes);
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  if (bos != null) {
                      try {
                          bos.close();
                      } catch (IOException e1) {
                          e1.printStackTrace();
                      }
                  }
                  if (fos != null) {
                      try {
                          fos.close();
                      } catch (IOException e1) {
                          e1.printStackTrace();
                      }
                  }
              }
              return file;
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
          /**
           * 创建文件
           * @param uploadPath
           * @param fileName
           * @return
           * @throws IOException
           */
          public static final File createNewFile(String uploadPath, String fileName) throws IOException {
              File file = new File(uploadPath + File.separator + fileName);
              if (!file.getParentFile().exists()) {
                  file.getParentFile().mkdirs();
              }
              if (!file.exists()) {
                  file.createNewFile();
              }
              return file;
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17

    1.2.2 拿来即用

    • 代码如下:
      在这里插入图片描述
    • 导包
      import cn.hutool.core.io.FileUtil;
      import cn.hutool.core.io.IoUtil;
      
      • 1
      • 2
    • 依赖
              <dependency>
                  <groupId>cn.hutoolgroupId>
                  <artifactId>hutool-allartifactId>
                  <version>5.4.0version>
              dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5

    2. 简单优化->上传、下载

    2.1 展示效果

    • 如下:
      在这里插入图片描述
      在这里插入图片描述
      在这里插入图片描述
    • 下载图片的地址直接用:"fileDownUrl": "http://127.0.0.1:8993/pet/file/upAndDown/downFile/20221012/b0a3164b6c94fe6c9d8b857bb75509fe.png",启动服务,地址栏输入此链接即可下载

    2.2 附代码

    1. 配置路径
      file:
        basePath: "/file/images/uploadPath"
        domain: "http://127.0.0.1:8993"
        downPath : "/pet/file/upAndDown/downFile"
      
      • 1
      • 2
      • 3
      • 4
    2. FileVo 实体
      package com.liu.susu.pojo.vo;
      
      import lombok.Data;
      
      /**
       * description
       * @author susu
       **/
      @Data
      public class FileVo {
      
          private String fileName;
      
          private String fileUpPath;
      
          private String fileDownUrl;
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
    3. 几个工具类
    • ① FileUtils.java

      package com.liu.susu.utils.file;
      
      import com.liu.susu.utils.DateUtils;
      import com.liu.susu.utils.Md5Utils;
      import org.apache.commons.io.FilenameUtils;
      import org.apache.commons.lang3.RandomStringUtils;
      import org.apache.commons.lang3.StringUtils;
      import org.springframework.web.multipart.MultipartFile;
      
      import java.io.BufferedOutputStream;
      import java.io.File;
      import java.io.FileOutputStream;
      import java.io.IOException;
      
      /**
       * description
       * @author susu
       **/
      public class FileUtils {
      
          /**
           * 创建文件
           * @param uploadPath
           * @param fileName
           * @return
           * @throws IOException
           */
          public static final File createNewFile(String uploadPath, String fileName) throws IOException {
              File file = new File(uploadPath + File.separator + fileName);
              if (!file.getParentFile().exists()) {
                  file.getParentFile().mkdirs();
              }
              if (!file.exists()) {
                  file.createNewFile();
              }
              return file;
          }
      
          /**
           * byte[]类型转File
           * @param bytes
           * @param uploadPath 文件输出目录
           * @param fileName 文件名
           * @return
           */
          public static File bytesToFile(byte[] bytes, String uploadPath, String fileName) {
              BufferedOutputStream bos = null;
              FileOutputStream fos = null;
              File file = null;
              try {
                  file = createNewFile(uploadPath,fileName);
                  fos = new FileOutputStream(file);
                  bos = new BufferedOutputStream(fos);
                  bos.write(bytes);
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  if (bos != null) {
                      try {
                          bos.close();
                      } catch (IOException e1) {
                          e1.printStackTrace();
                      }
                  }
                  if (fos != null) {
                      try {
                          fos.close();
                      } catch (IOException e1) {
                          e1.printStackTrace();
                      }
                  }
              }
              return file;
          }
      
          /**
           * 对文件进行编码
           * @param file
           * @return
           */
          public static final String GetCodingFileName(MultipartFile file) {
              String fileName = file.getOriginalFilename();
              String fileExtension = getFileExtension(file);
              fileName = DateUtils.getDatePath() + "/" + GetMd5EncodingFileName(fileName)
                      + "." + fileExtension;
              return fileName;
          }
      
          /**
           * 获取文件的扩展名
           * @param file
           * @return 文件的扩展名
           */
          public static final String getFileExtension(MultipartFile file) {
              String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
              if (StringUtils.isEmpty(fileExtension)) {
                  fileExtension = FileTypeUtils.getExtension(file.getContentType());
              }
              return fileExtension;
          }
      
          /**
           * 对文件名进行编码
           * @param fileName
           * @return
           */
          private static final String GetMd5EncodingFileName(String fileName) {
              fileName = fileName.replace("_", " ");
              return Md5Utils.hash(fileName + System.nanoTime() + RandomStringUtils.randomNumeric(3));
          }
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95
      • 96
      • 97
      • 98
      • 99
      • 100
      • 101
      • 102
      • 103
      • 104
      • 105
      • 106
      • 107
      • 108
      • 109
      • 110
      • 111
      • 112
      • 113
    • FileTypeUtils.java

      package com.liu.susu.utils.file;
      
      
      public class FileTypeUtils {
      
          public static final String IMAGE_PNG = "image/png";
      
          public static final String IMAGE_JPG = "image/jpg";
      
          public static final String IMAGE_JPEG = "image/jpeg";
      
          public static final String IMAGE_GIF = "image/gif";
      
          public static String getExtension(String prefix) {
              switch (prefix) {
                  case IMAGE_PNG:
                      return "png";
                  case IMAGE_JPG:
                      return "jpg";
                  case IMAGE_JPEG:
                      return "jpeg";
                  case IMAGE_GIF:
                      return "gif";
                  default:
                      return "";
              }
          }
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
    • DateUtils.java

      package com.liu.susu.utils;
      
      
      import java.time.LocalDate;
      import java.time.format.DateTimeFormatter;
      
      /**
       * description
       * @author susu
       **/
      public class DateUtils {
      
          public static final String getDatePath() {
              LocalDate localDate = LocalDate.now();
              DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
              return localDate.format(df);
          }
      
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
    • ④ Md5Utils.java
      参考:https://gitee.com/calvinhwang123/RuoYi-Process.

      package com.liu.susu.utils;
      
      import lombok.extern.slf4j.Slf4j;
      
      
      import java.security.MessageDigest;
      
      @Slf4j
      public class Md5Utils {
          private static byte[] md5(String s) {
              MessageDigest algorithm;
              try {
                  algorithm = MessageDigest.getInstance("MD5");
                  algorithm.reset();
                  algorithm.update(s.getBytes("UTF-8"));
                  byte[] messageDigest = algorithm.digest();
                  return messageDigest;
              } catch (Exception e) {
                  log.error("MD5 Error...", e);
              }
              return null;
          }
      
          private static final String toHex(byte hash[]) {
              if (hash == null) {
                  return null;
              }
              StringBuffer buf = new StringBuffer(hash.length * 2);
              int i;
      
              for (i = 0; i < hash.length; i++) {
                  if ((hash[i] & 0xff) < 0x10) {
                      buf.append("0");
                  }
                  buf.append(Long.toString(hash[i] & 0xff, 16));
              }
              return buf.toString();
          }
      
          public static String hash(String s) {
              try {
                  return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
              } catch (Exception e) {
                  log.error("not supported charset...{}", e);
                  return s;
              }
          }
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
    1. service

      package com.liu.susu.service.file;
      
      import com.liu.susu.pojo.vo.FileVo;
      import org.springframework.web.multipart.MultipartFile;
      
      import java.io.IOException;
      
      /**
       * description 图片上传下载
       * @author susu
       **/
      public interface MyFileService {
      
          FileVo uploadMultipartFile(MultipartFile upFile) throws IOException;
          
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      package com.liu.susu.service.file;
      
      import cn.hutool.core.io.FileUtil;
      import cn.hutool.core.io.IoUtil;
      import com.liu.susu.pojo.vo.FileVo;
      import com.liu.susu.utils.DateUtils;
      import com.liu.susu.utils.file.FileUtils;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.stereotype.Service;
      import org.springframework.web.multipart.MultipartFile;
      
      import java.io.File;
      import java.io.IOException;
      
      /**
       * description 图片上传下载
       * @author susu
       **/
      @Service
      public class MyFileServiceImpl implements MyFileService{
      
          @Value("${file.basePath}")
          private String basePath ;
      
          @Value("${file.domain}")
          private String domain;
      
          @Value("${file.downPath}")
          private String downPath;
      
      
          public FileVo uploadMultipartFile(MultipartFile upFile) throws IOException {
              byte[] bytes = IoUtil.readBytes(upFile.getInputStream());
              String codingFileNameWithDate = FileUtils.GetCodingFileName(upFile);
      //        String filePathAndName = basePath + File.separator + codingFileNameWithDate;
              String filePathAndName = basePath + "/" + codingFileNameWithDate;
              FileUtil.writeBytes(bytes, filePathAndName);
      
              FileVo fileVo = new FileVo();
              fileVo.setFileName(upFile.getOriginalFilename());
              fileVo.setFileUpPath(filePathAndName);
              fileVo.setFileDownUrl(domain + downPath + "/" + codingFileNameWithDate);
              return fileVo;
          }
      
      
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
    2. controller->FileUpAndDownController.java

      package com.liu.susu.controller.file;
      
      import cn.hutool.core.io.FileUtil;
      import cn.hutool.core.io.IoUtil;
      import com.github.xiaoymin.knife4j.annotations.ApiSupport;
      import com.liu.susu.common.ReturnCode;
      import com.liu.susu.common.ViewResultData;
      import com.liu.susu.pojo.vo.FileVo;
      import com.liu.susu.service.file.MyFileService;
      import io.swagger.annotations.Api;
      import io.swagger.annotations.ApiOperation;
      import lombok.extern.slf4j.Slf4j;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.http.HttpStatus;
      import org.springframework.http.MediaType;
      import org.springframework.web.bind.annotation.*;
      import org.springframework.web.multipart.MultipartFile;
      
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      import java.net.URLEncoder;
      
      /**
       * description 上传、下载图片
       * @author susu
       **/
      @RestController
      @RequestMapping("/pet/file/upAndDown")
      @Slf4j
      @Api(tags = "上传、下载图片")
      @ApiSupport(author = "披荆斩棘",order = 8)
      public class FileUpAndDownController {
      
          @Autowired
          private MyFileService fileService;
      
          @Value("${file.basePath}")
          private String basePath ;
      
      
          @PostMapping("/uploadFile")
          @ApiOperation("上传图片")
          public ViewResultData uploadFile(@RequestPart("upFile") MultipartFile upFile){
              try {
                  FileVo fileVo = fileService.uploadMultipartFile(upFile);
                  return new ViewResultData(ReturnCode.SUCCESS_000000,fileVo);
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return new ViewResultData(ReturnCode.FAIL_999999,"图片上传失败");
          }
      
          @GetMapping("/downFile/{fileDate}/{fileName}")
          @ApiOperation("下载传图片")
          public void downFile(HttpServletResponse response,
                               @PathVariable(value = "fileDate",required = true) String fileDate,
                               @PathVariable(value = "fileName",required = true) String fileName){
              //根据fileName查寻到filePath
              String filePath = basePath + "/" + fileDate + "/" +fileName;
              byte[] bytes = FileUtil.readBytes(filePath);
              if (bytes == null) {
                  log.info("下载的文件不存在");
                  response.setStatus(HttpStatus.NOT_FOUND.value());
                  return;
              }
              try {
                  // 设置 header 和 contentType
                  response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                  response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                  // 输出文件
                  IoUtil.write(response.getOutputStream(), false, bytes);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
      
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80

    3. 附项目

  • 相关阅读:
    紫草酸人血清白蛋白HSA纳米粒|乳香酸卵清白蛋白OVA纳米粒|表白桦脂酸人血清白蛋白纳米粒Epibetulinic Acid-HSA
    Win10中Pro/E鼠标滚轮不能缩放该怎么办?
    【Pytorch深度学习实战】(5)卷积神经网络(CNN)
    Domino服务器SSL证书安装指南
    腾讯云centos7.6安装jdk
    html骨架标签
    vulnhub BTRSys: v2.1
    前端开发常用哪些工具软件?
    【java学习—八】==操作符与equals方法(2)
    微信小程序官方组件目录结构
  • 原文地址:https://blog.csdn.net/suixinfeixiangfei/article/details/127265192