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();
}
}