springboot 頭像上傳 檔案流儲存 檔案流返回瀏覽器檢視 區分作業系統 windows 7 or linux
阿新 • • 發佈:2018-12-10
//我的會員中心 頭像上傳介面/*windows 除錯*/@Value("${appImg.location}")private String winPathPic;/*linux 使用*/@Value("${img.location}")private String linuxPathPic;@PostMapping(value = "/file")public String file() { return "file";}@ApiOperation(value = "會員頭像檔案上傳")@ApiImplicitParams({})@RequestMapping(value = "/appMbrImgUploadFile", method = RequestMethod.POST)@ResponseBodypublic Object appMbrImgUploadFile(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) { Subject currentUser = SecurityUtils.getSubject(); ShiroUser shiroUser = null; Session session = currentUser.getSession(); String mobile = session.getAttribute("username") == null ? "" : String.valueOf(session.getAttribute("username")); if (mobile.equals("")) { return setModelMap(new ModelMap(), HttpCode.EFFECT_OF_TOKEN.value(), "token已經失效,請登入", null); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); //時間路徑 String fileTime = sdf.format(new Date()); // 檔名 String fileName = file.getOriginalFilename(); // 字尾名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); //圖片格式校驗 String reg = "(.png)$"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(suffixName); boolean valiRst = matcher.find(); if (!valiRst) { return setModelMap(new ModelMap(), HttpCode.PICTURE_FORMAT_CHECK_EXCEPTION.value(), "圖片格式異常", null); } if (file.isEmpty()) { System.out.println("檔案為空"); logger.error("檔案流為空異常"); return setModelMap(new ModelMap(), HttpCode.FILE_STREAM_EMPTY.value(), "檔案流為空異常", null); } //判斷作業系統 String os = System.getProperty("os.name"); System.out.println(os); //定義路徑 String picPathReal=""; if(os!=null&&os.contains("Windows 7")){ System.out.println("Windows 7"); picPathReal=winPathPic; }else{ //linux picPathReal=linuxPathPic; } // 新檔名 fileName = UUID.randomUUID() + suffixName; // 檔案目錄 String diectFile=picPathReal+"/"+fileTime; File dest = new File(diectFile); dest.setWritable( true, false); if (!dest.exists()) { dest.mkdirs(); } //建立檔案 圖片 File filePic = new File(diectFile+File.separator, fileName); try { file.transferTo(filePic); } catch (IOException e) { e.printStackTrace(); } LSysMember sysMember = new LSysMember(); LSysMemberVo userInfo = new LSysMemberVo(); //返回指定圖片檔案路徑 完整介面地址 //儲存地址處理 String savePath="/lSysMember/noLogin/readImageFile?url="+picPathReal+File.separator+fileTime+File.separator+fileName; //String filename = "/lSysMember/noLogin/readImageFile?url="+savePath+File.separator + fileTime + File.separator + fileName; //查詢會員基本資訊 sysMember = memberService.findLoginMemberInfo(mobile); //執行更新頭像更新操作 sysMember.setAvatar(savePath); try { sysMember = memberService.appMbrImgUploadFile(sysMember); userInfo = memberService.findLoginMemberInfoByMobile(mobile); } catch (Exception e) { logger.error("請求異常----", e); throw new CallChainException(); } //更新session session.setAttribute("shiroUser", userInfo); return setSuccessModelMap(savePath);}
@ApiOperation(value = "返回指定地址的檔案流")@ApiImplicitParams({ @ApiImplicitParam(name = "url", value = "圖片地址", required = true, paramType = "query", defaultValue = "\\20180912\\7cd2e1a3-a087-4e25-aac8-2bdf8e274c6f.png"),})@RequestMapping(value = "/noLogin/readImageFile",method =RequestMethod.GET)@ResponseBodypublic void getUrlFile(String url, HttpServletRequest request, HttpServletResponse response) { File file = new File(url); // 字尾名 String suffixName = url.substring(url.lastIndexOf(".")); //判斷檔案是否存在如果不存在就返回預設圖示 if (!(file.exists() && file.canRead())) { file = new File(request.getSession().getServletContext().getRealPath("/") + "resource/icons/auth/root.png"); } FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; int length = inputStream.read(data); inputStream.close(); //setContentType("text/plain; charset=utf-8"); 文字 response.setContentType("image/png;charset=utf-8"); OutputStream stream = response.getOutputStream(); stream.write(data); stream.flush(); stream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}