国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Jersey 文件下載

2019-11-11 01:38:01
字體:
來源:轉載
供稿:網友

Jersey 文件下載

Jersey實現文件下載有兩種方式,一種是直接將文件作為響應體,一種是使用StreamingOutput對象作為響應體。

一、使用文件對象作為響應體

Jersey支持直接使用文件對象作為響應體實現下載功能,但是需要注意的是需要進行判斷文件對象是否存在,否則會報Request failed.

package cn.lx.resource;import javax.ws.rs.*;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;import java.io.File;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;/** 測試下載文件 * Created by lxliuxuan on 2017/2/7. */@Path("/sign")public class SignResourceT { @GET @Path("/get") @PRoduces(MediaType.application_OCTET_STREAM) public Response getAll(@QueryParam("filePath") String filePath){ File file = new File(filePath); //如果文件不存在,提示404 if(!file.exists()){ return Response.status(Response.Status.NOT_FOUND).build(); } String fileName = null; try { fileName = URLEncoder.encode("下載測試.xls", "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } return Response .ok(file) .header("Content-disposition","attachment;filename=" +fileName) .header("Cache-Control", "no-cache").build(); }}

二、使用StreamingOutput對象作為響應體

這種方式可以使用在java做Excel文件導出時,直接從數據庫讀取數據,將數據寫入到輸出流,響應給瀏覽器,不需要文件存在。

@GET@Path("/getByStream")@Produces(MediaType.APPLICATION_OCTET_STREAM)public Response getAllByStream(@QueryParam("filePath") String filePath){ FileStream fileStream = new FileStream("d:/test/poi/userSign.xls"); String fileName = null; try { fileName = URLEncoder.encode("下載測試.xls", "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } return Response .ok(fileStream) .header("Content-disposition","attachment;filename=" +fileName) .header("Cache-Control", "no-cache").build();}class FileStream implements StreamingOutput{ private String filePath; public FileStream(String filePath) { this.filePath = filePath; } public void write(OutputStream output) throws IOException, WebApplicationException { File file = new File(filePath); //如果文件不存在,提示404 if(!file.exists()){ throw new WebApplicationException(404); } output = new FileOutputStream(file); output.flush(); output.close(); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石门县| 梁河县| 郴州市| 东阿县| 丰县| 东城区| 于都县| 司法| 长治县| 沁水县| 怀远县| 英山县| 三亚市| 濮阳县| 安陆市| 万载县| 察哈| 凤阳县| 民县| 西充县| 阜平县| 吉安县| 涟源市| 会东县| 宣威市| 湟源县| 渭南市| 望谟县| 筠连县| 瑞丽市| 文登市| 赣榆县| 汾西县| 剑河县| 东丰县| 周口市| 松原市| 怀仁县| 石景山区| 福建省| 化德县|