关于Jersey解决文件下载的问题

一心想着如何解决jersey下载文件的问题, 在度娘上面几乎找不到对应的资料,没办法,啃文档看源码。 看到jersey的扩展MessageBodyWriter。想着应该可以通过这个去解决。
后来又想想,jersey和springmvc同是restful的规范实现, 应该能从springMVC上借鉴,折腾半天无果, 不小心看到jersey支持File, 唉, 暗叹自己走弯路, 老想着复杂的方式去解决!

上源码

@Path("file")
public class FileResource {
@GET
@Path("pdf/{pdf}")
@Produces("pdf/*")
public Response getPDF(@PathParam("pdf") String pdf,
@Context ServletContext application) {
String realPath = application.getRealPath("/images");
realPath = "D:/books/aa.xlsx";
File file = new File(realPath);
if (!file.exists()) {
throw new WebApplicationException(404);
}

String mt = new MimetypesFileTypeMap().getContentType(file);
return Response
.ok(file, mt)
.header("Content-disposition",
"attachment;filename=" + pdf + ".xlsx")
.header("ragma", "No-cache")
.header("Cache-Control", "no-cache").build();
}
}


简单吧, 就几行代码!效率哇效率!

为方便其他人员测试, 把pom.xml共享给大家!

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>simple-service-webapp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>simple-service-webapp</name>

<build>
<finalName>simple-service-webapp</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->
</dependencies>
<properties>
<jersey.version>2.12</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>



如果编辑报错, 记得增加servlet.jar包!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值