瀏覽器文件下載:如果你想在瀏覽器中實現下載功能--一些原本不默認下載的文件,如:jpg、xml等。
圖片顯示(流形式):如果你想在瀏覽器中顯示圖片,而圖片不是一個靜態文件(沒有url地址)
那我們應該怎么做呢?
分析:
瀏覽器獲得文件是通過http協議的,
所以只要我設置好請求(request)返回的響應(response)的一些信息應該就行了,
那就是設置響應(response)頭的一些信息嘍。
解決:
瀏覽器文件下載設置:
Content-Type:application/octet-stream // 未分類的二進制數據
Content-Disposition:attachment;filename=yourFileName //附件形式處理,文件名為yourFileName
Content-Length:yourFile.length //文件的大小
而文件以流形式輸出為瀏覽器就行了。
這樣瀏覽器就能識別該文件是通過附件的形式下載的了。
java的servlet代碼:
public HttpServletResponse getFile(String path,HttpServletRequest request, HttpServletResponse response) { try { File file = new File(request.getRealPath("/")+"/"+path); String filename = file.getName(); InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); // 設置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO-8859-1")); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; }
java的restlet主要代碼:
final byte[] bpmnBytes = //文件流字節; Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(fileName); OutputRepresentation output = new OutputRepresentation(org.restlet.data.MediaType.APPLICATION_OCTET_STREAM) { public void write(OutputStream os) throws IOException { os.write(bpmnBytes); os.flush(); } }; output.setDisposition(disposition); return output;
圖片(流形式)顯示設置:
Content-Type:image/jpeg // jpeg、jpg、jpe、jfif形式的圖片
Content-Length:yourImg.length //圖片大小
而圖片以流形式輸出為瀏覽器就行了。
java的servlet代碼:
public HttpServletResponse getImage(String path,HttpServletRequest request, HttpServletResponse response) { try { File file = new File(request.getRealPath("/")+"/"+path); String filename = file.getName(); InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); // 設置response的Header response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("image/jpeg"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; }
java的restlet主要代碼:
final byte[] result = //圖片流字節; return new OutputRepresentation(MediaType.IMAGE_PNG) { public void write(OutputStream os) throws IOException { os.write(result); os.flush(); os.close(); } };
這樣瀏覽器就能正確識別該圖片,並在瀏覽器中識別出來。
當然也可以是img標簽的src中顯示。