通過HTTP請求圖片,同時轉為二進位制流返回
阿新 • • 發佈:2019-02-04
通過HTTP獲取圖片,經過servlet轉為二進位制流後再輸出出來,最後我們可以通過訪問service直接得到圖片流同時顯示
程式碼:
[java]- /**
- * 獲取圖片
- * @param request
- * @param response
- */
- publicvoid GetImage(HttpServletRequest request
- , HttpServletResponse response){
- try {
- URL url = new URL("http://sd/www/image/co.gif");
- HttpURLConnection con = (HttpURLConnection)url.openConnection();
- con .setRequestMethod("GET");
- con .setConnectTimeout(4 * 1000);
- InputStream inStream = con .getInputStream();//通過輸入流獲取圖片資料
- byte data[] = readInputStream(inStream);
- inStream.read(data); //讀取該資料
- inStream.close();
- response.setContentType("image/jpg"
- OutputStream o = response.getOutputStream();
- o.write(data);
- o.flush();
- o.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- publicstaticbyte[] readInputStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = newbyte[2048];
- int len = 0;
- while( (len=inStream.read(buffer)) != -1 ){
- outStream.write(buffer, 0, len);
- }
- inStream.close();
- return outStream.toByteArray();
- }
- /**
- * 上傳圖片
- * @param request
- * @param response
- */
- publicvoid uploadHomeImage(HttpServletRequest request
- , HttpServletResponse response){
- //儲存檔案,同時獲取表單中的輸入值對
- Map<String, String> nameValuePair = new HashMap<String, String>();
- //home圖片儲存物件
- HomeImage homeImage = new HomeImage();
- //獲取儲存的地址,捕獲引數值對
- String imageUrl = saveUploadFile(request, "/Upload/HomeImage/", nameValuePair);
- homeImage.setImageUrl(imageUrl);
- homeImage.setUploadDate(new Date());
- settingService.saveOrUpdateHomeImage(homeImage);
- //資訊介面顯示類
- HomeImagePage responsePage = settingService.getWebHomePage();
- //將頁面顯示資料類轉化為JSON,並返回到前臺
- responseOutWithJson(response, responsePage);
- response.setStatus(HttpServletResponse.SC_OK);
- }