java图片上传

1、java将图片转成base64返回前端,前端解析展示

  1 /***
  2      * 上传证明材料
  3      * @param files
  4      * @param request
  5      * @return
  6      */
  7     @RequestMapping(value = "/bitchUploadFile", method = {RequestMethod.POST, RequestMethod.GET})
  8     @ResponseBody
  9     public ResponseResult bitchUploadFile(@RequestParam(value = "files", required = false) MultipartFile[] files, HttpServletRequest request) {
 10         log.info("进入上传证件方法。。。");
 11         ResponseResult res = new ResponseResult();
 12         byte[] data = null;
 13         List<String> urls = new ArrayList<>();
 14         if (null != files && files.length > 0) {
 15             for (MultipartFile file : files) {
 16                 try {
 17                     // 判断图片大小是否大于1M
 18                     if (file == null || file.isEmpty() || file.getSize() > UPLOAD_FILE_SIZE) {
 19                         return ResponseResult.FAIL("上传文件为空或者超过规定的大小");
 20                     }
 21                     String[] suffixNamesNotDel = {"jpg", "jpeg", "png", "JPG", "JPEG", "PNG"};
 22                     String[] suffixNames = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"};
 23                     List<String> suffixNamesNotDelList = Arrays.asList(suffixNamesNotDel);
 24                     List<String> suffixNamesList = Arrays.asList(suffixNames);
 25                     // 获取图片的文件名
 26                     String fileName = file.getOriginalFilename();
 27                     int dotIndex = fileName.lastIndexOf(".");
 28                     if (dotIndex < 0) {
 29                         dotIndex = fileName.length();
 30                     }
 31                     //通过判断后缀判断
 32                     String suffixName = fileName.substring(dotIndex);
 33                     //根据文件头名判断文件实际类型
 34                     boolean su = suffixNamesList.contains(suffixName);
 35                     // 获取图片的扩展名
 36                     String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
 37                     if (su) {
 38                         String uploadUrl = "";
 39                         //上传文件返回服务器存储路径(公用方法)
 40                         String db = "demo";
 41                         uploadUrl = saveFile(extensionName, db, file);
 42                         //使用base64编码返回前端
 43                         InputStream in = new FileInputStream(uploadUrl);
 44                         data = new byte[in.available()];
 45                         in.read(data);
 46                         in.close();
 47                         //对字节数组进行base64编码
 48                         BASE64Encoder encoder = new BASE64Encoder();
 49                         String strBase64 ="data:image/jpeg;base64,"+ encoder.encode(data);
 50                         urls.add(strBase64);
 51                         res = ResponseResult.SUCCESS(urls);
 52                     } else {
 53                         return ResponseResult.FAIL("请上传格式为jpg和png的图片文件");
 54                     }
 55                 } catch (Exception e) {
 56                     log.error("上传图片失败" + e);
 57                     return ResponseResult.FAIL("上传图片失败");
 58                 }
 59             }
 60         }
 61         return res;
 62     }
 63 
 64 
 65     /**
 66      * @param extensionName 原文件扩展名
 67      * @param db            Business differentiation区分不同业务,避免上传文件名相同
 68      * @param filedata      上传的文件数据
 69      * @Description 文件上传到配置文件 common.properties中的image.storage.root.path路径上
 70      */
 71     public String saveFile(String extensionName, String db, MultipartFile filedata) {
 72         // 新的图片文件名 = 获取时间戳+"."图片扩展名
 73         String newFileName = db + String.valueOf(System.currentTimeMillis()) + "." + extensionName;
 74         String saveFilePath = "";
 75         String preImgUrl = "";
 76         FileOutputStream out = null;
 77         try {
 78             // 根据配置文件获取服务器图片存放路径
 79             //这里封装了读取配置文件的方法 配置文件中有图片的存放地址和获取地址
 80             // 根据配置文件获取图片上传路径
 81             saveFilePath = "D:/aWangzhaung/tools";
 82             preImgUrl = "D:/aWangzhaung/tools";
 83             /* 构建文件目录 */
 84             File fileDir = new File(saveFilePath);
 85             if (!fileDir.exists()) {
 86                 fileDir.mkdirs();
 87             }
 88             out = new FileOutputStream(saveFilePath + File.separator
 89                     + newFileName);
 90             // 写入文件
 91             out.write(filedata.getBytes());
 92             out.flush();
 93         } catch (Exception e) {
 94             log.error("上传图片失败" + e);
 95             return "";
 96         } finally {
 97             if (out != null) {
 98                 try {
 99                     out.close();
100                 } catch (IOException e) {
101                     e.printStackTrace();
102                 }
103             }
104         }
105         return preImgUrl + "/" + newFileName;
106 }

2、Java 前端将图片转成base64上传

 1      /***
 2      * 上传证明材料
 3      * @param tempMap
 4      * @return
 5      */
 6     @RequestMapping(value = "/bitchUploadFile", method = RequestMethod.POST)
 7     @ResponseBody
 8     public ResponseResult bitchUploadFile(@RequestBody Map<String, Object> tempMap, HttpServletRequest request) {
 9         ResponseResult res = new ResponseResult();
10         try {
11             String imageUrl = "";
12             String preImgUrl = "";
13             String file = (String) tempMap.get("file");
14             log.info("file===========" + file);
15             try {
16                 if (StringUtils.isEmpty(file)) {
17                     return ResponseResult.FAIL("参数异常");
18                 }
19                 String[] jsonParames = file.split(":");
20                 String consultId = getRandomFileName();22                 if (jsonParames[1] != null && !"".equals(jsonParames[1])) {
23                     String savePath = basePath(consultId);
24                     String imageBase = jsonParames[1];
25                     try {
26                         // 文件名称
27                         String baseFileName = UUID.randomUUID().toString().replace("-", "").toUpperCase() + ".png";
28                         imageBase = imageBase.split(";base64,")[1];
29                         FileOutputStream out;
30 
31                         out = new FileOutputStream(savePath + baseFileName);
32                         BASE64Decoder decoder = new BASE64Decoder();
33                         byte[] imageByte = decoder.decodeBuffer(imageBase);
34                         // 调整异常数据
35                         for (int i = 0; i < imageByte.length; ++i) {
36                             if (imageByte[i] < 0) {
37                                 imageByte[i] += 256;
38                             }
39                         }
40                         out.write(imageByte);
41                         out.close();
42                         //图片存储路径
43                         preImgUrl = "/static/images/image";
44                         imageUrl = preImgUrl + "/" + consultId + "/" + baseFileName;
45                         //返回图片存储url给前端
46                         res = ResponseResult.SUCCESS(imageUrl);
47                     } catch (FileNotFoundException e) {
48                         e.printStackTrace();
49                     } catch (IOException e) {
50                         e.printStackTrace();
51                     }
52                 } else {
53                     res = ResponseResult.FAIL("图片格式异常");
54                 }
55             } catch (Exception e) {
56                 e.printStackTrace();
57                 res = ResponseResult.FAIL("接口调用异常");
58             }
59         } catch (Exception e) {
60             e.printStackTrace();
61         }
62 
63         return res;
64     }
65     
66     private String basePath(String consultId) {
67         // 图片存放路径
68         String saveFilePath = "/nfs/static/images/image";
69         String savePath = saveFilePath + "/" + consultId + "/";
70         File basePath = new File(savePath);
71         // 目录不存在就创建目录
72         if (!basePath.exists()) {
73             basePath.mkdirs();
74         }
75         return savePath;
76     }
77 
78     /**
79      * 获取随机数 19位 包含当前时间
80      *
81      * @return
82      */
83     public String getRandomFileName() {
84 
85         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
86         Date date = new Date();
87         String str = simpleDateFormat.format(date);
88         Random random = new Random();
89         // 获取5位随机数
90         int ranNum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
91 
92         return str + ranNum;
93     }
原文地址:https://www.cnblogs.com/4king/p/13212866.html