您的位置:首页 > 其它

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

2014-09-14 22:39 239 查看
一心想着如何解决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包!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: