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

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

Jersey 文件下載

2019-11-11 03:26:19
字體:
來源:轉載
供稿:網友

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(); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永年县| 云浮市| 军事| 五莲县| 辽阳市| 渝中区| 涪陵区| 贵阳市| 高碑店市| 维西| 托克逊县| 阿坝| 定西市| 中江县| 洪洞县| 美姑县| 抚州市| 三门县| 乌什县| 博罗县| 广灵县| 桂东县| 白沙| 高淳县| 龙门县| 防城港市| 天津市| 桦川县| 罗田县| 黄平县| 上思县| 梁河县| 云南省| 建水县| 尉氏县| 浙江省| 黄冈市| 巴青县| 柘城县| 扶沟县| 宁南县|