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

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

Jersey 文件下載

2019-11-11 02:12:41
字體:
來源:轉載
供稿:網友

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(); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邳州市| 景德镇市| 河曲县| 株洲县| 沙河市| 磴口县| 景泰县| 綦江县| 石楼县| 昆明市| 方山县| 雅安市| 惠水县| 吴堡县| 进贤县| 新巴尔虎右旗| 城步| 白河县| 全椒县| 昭苏县| 莲花县| 图片| 九龙县| 任丘市| 苍山县| 宜州市| 虞城县| 会泽县| 石屏县| 四会市| 洪雅县| 广安市| 桐庐县| 克东县| 陆丰市| 松桃| 石景山区| 百色市| 吉木萨尔县| 晋州市| 长治县|