java Web讀取圖片顯示
阿新 • • 發佈:2019-01-26
工具類:
public static void saveFile(MultipartFile file,HttpServletRequest request,String name) throws IOException{ String path=upload_img_path; System.out.println("path:"+path); File folder = new File(path); if(!folder.exists()){ folder.mkdirs(); } byte[] bytes = file.getBytes(); BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File(path+"/"+name))); stream.write(bytes); stream.close(); }
讀取流顯示圖片
@RequestMapping("/image") @ResponseBody public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception{ String JPG="image/jpeg;charset=GB2312"; String iname=request.getParameter("iname"); if(!StringUtil.isEmpty(iname)){ // 本地檔案路徑 String filePath = UploadUtil.upload_img_path+"\\"+iname; File file = new File(filePath); // 獲取輸出流 OutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); // 讀資料 byte[] data = new byte[fileInputStream.available()]; fileInputStream.read(data); fileInputStream.close(); // 回寫 response.setContentType(JPG); outputStream.write(data); outputStream.flush(); outputStream.close(); } }