登录
注册
写文章
发现
工具
springboot接收app端(ios、android等)上传文件流
_3t3lfz KEKfID
编辑文章
springboot接收app端(ios、android等)上传文件流
asfx站长
2020.11.03 20:30:31
阅读
1036
以上传图片为例: ``` // 支持app端一次上传多张图片 @PostMapping("/upload/image/app") @ResponseBody public List<JSONObject> uploadAppImage(HttpServletRequest request, HttpServletResponse response) throws Exception{ MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap(); List<JSONObject> result = new ArrayList<>(); for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){ MultipartFile file = entry.getValue(); JSONObject res = uploadImage(file, "app", request); log.debug("-> app upload file: {}", res); result.add(res); } return result; } /** * @Description 执行上传图片 * @Param [file] * @return com.alibaba.fastjson.JSONObject **/ private JSONObject uploadImage(MultipartFile file, String source, HttpServletRequest request){ JSONObject res = new JSONObject(); if(file == null){ res.put("success", 0); res.put("state", "0"); res.put("message", "upload fail! no file!"); return res; } String busType = request.getParameter("busType"); log.debug("上传文件的自定义业务类型,{}", busType); String rootPath = webConfig.getUploadPath();//根路径 String relativePath = DateUtils.getNow(DateUtils.YM_D) + File.separator;//相对路径,yyyyMM/dd/ String trueFileName = file.getOriginalFilename(); String suffix = trueFileName.substring(trueFileName.lastIndexOf(".")); String uuid = UUIDUtils.get32UUID(); String fileName = uuid + suffix; File targetFile = new File(rootPath + relativePath, fileName); File parentFile = targetFile.getParentFile(); //保存 try { if(!parentFile.exists()){ parentFile.mkdirs(); } file.transferTo(targetFile); String fileRelativePath = relativePath + fileName;//上传文件的存储相对路径 String imgServer = webConfig.getImgServer(); // 组装上传后的图片可访问链接地址返回给前端 String url = imgServer + "image?path=" + URLEncoder.encode(fileRelativePath, Constant.charset_utf_8); // TODO 保存数据库文件表... res.put("url", url); res.put("success", 1);//上传成功 res.put("state", "1");//字符串类型的成功状态 res.put("message", "upload success!");//提示信息 log.debug("上传图片成功,访问url, {}", url); } catch (Exception e) { e.printStackTrace(); res.put("state", "0"); res.put("success", 0);//上传失败 res.put("message", "upload fail! " + e.getMessage()); } return res; } ```
我的主页
退出