前言
本地下載檔案其實之前就接觸過,但是一直存在疑問就是下載必須開啟新的視窗,通過ajax請求無法達到下載檔案的目的,所以一般對於異常的捕捉我自訂反應在介面上我通常都是再寫一個介面,把各種異常都考慮到,然後執行新的下載命令。如果有更好的方法可以告知我,本篇主要講的就是下載檔案的兩種方式以及將圖片展示在瀏覽器中。當然這兩種實現都離不開response的設定。 內容 通過瀏覽器展示圖片
目前公司是有這方面的需求的,將圖片下載到了本地,但是並不在圖片伺服器上,也不再項目的根目錄下,如何在找到圖片,並且將圖片展示到img標籤中,通過這種方式是可以實現的
@ResponseBody @RequestMapping(value = "/test.action") public void base64ToFile(String base64, String fileName, HttpServletResponse response) { File file = null; InputStream fis = null; OutputStream fos = null; try { file = new File("G:/image/2.jpg");//假設了圖片的路徑 fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); // 設定response的header response.reset(); response.setHeader("Content-Type", "image/jpg"); response.addHeader("Content-Length", "" + file.length()); fos = new BufferedOutputStream(response.getOutputStream()); fos.write(buffer); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (Exception e2) { e2.printStackTrace(); } } } }
在瀏覽器中圖片展示如下
下載檔案
1.這是我第一次接觸的方式,在這裡使用到的httpheaders和HttpStatus都是springmvc中包含的類,都是一些封裝好的枚舉類,如果想要更多的瞭解這些東西可以去網上參考部落格
@RequestMapping(value = "/downFile.action") public ResponseEntity<byte[]> downFile() { HttpHeaders headers = new HttpHeaders(); InputStream fis = null; byte[] buffer = null; try { String filepath = "G:/image/2.jpg"; File file = new File(filepath); String filename = file.getName(); headers.setContentDispositionFormData("attachment", filename); fis = new BufferedInputStream(new FileInputStream(file)); buffer= new byte[fis.available()]; fis.read(buffer); return new ResponseEntity<byte[]>(buffer,headers,HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<byte[]>(buffer,headers,HttpStatus.NOT_FOUND); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
總結
其實在瞭解這些東西的時候我們對於瀏覽器所報的異常情況就可以很快的給出解決方案,對於加快網頁的開發非常有協助,學無止境。