RESTEasy实现上传下载文件

    近期,使用RESTEasy实现了上传下载文件。这次我是使用guice来注册服务,要想使用guice来注册服务,需要修改web.xml:

将:

<context-param>  
	<param-name>resteasy.scan</param-name>  
	<param-value>true</param-value>  
</context-param>  
<!-- 不加监听器就会造成Tomcat无法解析html -->  
<listener>  
	<listener-class>  
		org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap  
	 </listener-class>  
</listener>  
修改成:
<context-param>
    <param-name>resteasy.guice.modules</param-name>
    <param-value>org.oliver.module.FileModule</param-value>
  </context-param>
  
  <listener>
    <listener-class>
            org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
    </listener-class>
  </listener>

配置resteasy.guice.modules来指明注册服务类FileModule。FileModule实现了com.google.inject.Module接口,并实现了它的configure(Binderbinder)方法,如下:

import org.oliver.resource.DownloadFileResource;
import org.oliver.resource.FilePath;
import org.oliver.resource.UploadFileResource;

import com.google.inject.Binder;
import com.google.inject.Module;

/**
 * 注册服务
 * 
 * @author Oliver
 * 
 */
public class FileModule implements Module {
	
	public void configure(final Binder binder) {
		binder.bind(UploadFileResource.class);
		binder.bind(DownloadFileResource.class);
		binder.bind(FilePath.class);
	}
}

这样三个服务类注册完成。现在就开始编写上传下载文件。

上传文件

1、上传文件页面设计如下:

<form action="./serivce/upload/file" method="post" enctype="multipart/form-data">
	文件名:<input type="text"  name="fileName" id="fileName" readonly="true" value=""/><br/>
	文件:<input type="file" name="file" id="file" value=""/><br/>
	<input type="submit" value="提交" />
</form>


2、文件类定义如下:

import javax.ws.rs.FormParam;
import javax.ws.rs.core.MediaType;

import org.jboss.resteasy.annotations.providers.multipart.PartType;

public class DisKFile {

	private String fileName;
	private byte[] fileDate;
	
	public DisKFile() {
	}

	public String getFileName() {
		return fileName;
	}

	@FormParam("fileName")
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public byte[] getFileDate() {
		return fileDate;
	}

	@FormParam("file")
	@PartType(MediaType.APPLICATION_OCTET_STREAM)
	public void setFileDate(byte[] fileDate) {
		this.fileDate = fileDate;
	}
}

3、服务实现如下:

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.io.FileUtils;
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import org.oliver.model.DisKFile;
import org.oliver.model.Message;

@Path("/upload")
public class UploadFileResource {

	public static final String DIRCTORY = "E:/temp";

	// @PUT
	@POST
	@Path("/file")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces("application/json;charset=UTF-8")
	public Response upload(@MultipartForm DisKFile diskFile,
			@Context HttpServletRequest request) {
		try {
			initDirectory(DIRCTORY);
			String newName = getNewName(diskFile.getFileName());
			File file = new File(DIRCTORY + "/" + newName);
			FileUtils.writeByteArrayToFile(file, diskFile.getFileDate());
		} catch (IOException e) {
			e.printStackTrace();
		}
		Message message = new Message(true, "文件上传成功!");
		return Response.ok(message).build();
	}

	/**
	 * 初始化目录
	 * 
	 * @param path
	 * @throws IOException
	 */
	private void initDirectory(String path) throws IOException {
		File dir = new File(path);
		if (!dir.exists()) {
			FileUtils.forceMkdir(dir);
		}
	}
	
	private String getNewName(String fileName) {
		String newFileName = "Unkonwn";
		if (fileName != null) {
			int index = fileName.lastIndexOf(".");
			if (index != -1)
				newFileName = UUID.randomUUID().toString()+fileName.substring(index);
		}

		return newFileName;
	}

}

4、运行效果

    在浏览器中输入http://localhost:8080/UploadAndDownLoadFile/,进入如下页面:


    点击“提交”,返回json:
{"status":true,"infor":"文件上传成功!"}

下载文件

    下载文件就相对简单,只用后端将文件流写入 javax.ws.rs.core.Response中即可,浏览器会自动解析。

1、服务实现如下:

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

@Path("/download")
public class DownloadFileResource {

	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public Response download(@QueryParam(value = "fileName") String fileName,
			@Context HttpServletRequest request) {
		if(fileName == null||fileName.isEmpty()){
			ResponseBuilder response = Response.status(Status.NOT_FOUND);
			return response.build();
		}
		String filePath = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes/", "");
		File file = new File(filePath+"/file/"+fileName);
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition", "attachment; filename=\""+fileName+"\"");//"attachment; filename=\"fileName.txt\""
		return response.build();
	}

}

2、运行效果

    在浏览器下输入: http://localhost:8080/UploadAndDownLoadFile/serivce/download?fileName=fileName.pdf,就能成功下载图片


附录

    下载文件放在WebContent/file/下。在web工程下获取这个路径,可是费了我不少时间。本人在网上搜寻了多种方式,记录在本工程的FilePath.java(服务类)。可以在上传文件页面下点击“查看后台获取文件路径方式”查看。
    不知道怎样把工程附在博客里面,所有上传到CSDN,这是下载地址, http://download.csdn.net/detail/zhangzhuang1127/6742855


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值