Jersey 文件下载

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();  
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值