`
jacktea
  • 浏览: 6742 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

SpringMVC 文件下载

    博客分类:
  • J2EE
 
阅读更多

写了个下载封装代码如下:

 

    DownloadHelper.java(下载帮助类,当请求响应方法反回此对象,并用@ResponseBody声明时自动实现下载功能)

 

public class DownloadHelper {
	
	
	private boolean forOpen = false;
	
	private boolean clearFile = false;
	
	private Map<String,String> headers = new HashMap<String, String>();
	
	private File file;
	
	private String content;
	
	private Charset charset;
	
	

	public DownloadHelper() {
		super();
		setContentType(null);
	}

	public boolean isForOpen() {
		return forOpen;
	}
	
	public boolean isClearFile() {
		return clearFile;
	}
	/**
	 * 设置是否清理文件
	 * @param clearFile
	 */
	public void setClearFile(boolean clearFile) {
		this.clearFile = clearFile;
	}

	/**
	 * 如果下载对象,浏览器默认能打开的话,可以设置此属性为true在当前浏览器中打开
	 * @param forOpen
	 */
	public void setForOpen(boolean forOpen) {
		this.forOpen = forOpen;
	}

	public Map<String, String> getHeaders() {
		return headers;
	}

	public void setHeaders(Map<String, String> headers) {
		this.headers = headers;
	}

	public File getFile() {
		return file;
	}

	public String getContent() {
		return content;
	}

	public Charset getCharset() {
		return charset;
	}

	public void setContent(String content,Charset charset){
		setCharset(charset);
		setContentLength(content.getBytes(charset).length);
		this.content = content;
	}
	
	/**
	 * 设置要下载的文件
	 * @param file
	 */
	public void setFile(File file) {
		this.file = file;
		if (file != null) {
			setFileName(file.getName());
			setContentLength(file.length());
			try {
				Charset charset = FileUtil.getFileEncoding(file);
				if (forOpen) {
					setCharset(charset);
				}
			} catch (IOException e) {
				
			}
		}
	}
	
	/**
	 * 设置要下载的文件名,界面上弹出框的提示,此方法必须在setFile方法之后调用,如果不调用使用默认setFile方法参数的文件名
	 * @param fileName
	 */
	public void setFileName(String fileName){
		fileName = fileName==null&&getFile()!=null ? getFile().getName() : fileName;
		if(fileName==null)return;
		StringBuilder sb = new StringBuilder();
		if(forOpen){
			sb.append("inline;");
		}else{
			sb.append("attachment;");
		}
		if(!fileName.trim().equals("")){
			sb.append("filename=\"");
			try {
				sb.append(new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
			} catch (UnsupportedEncodingException e) {				
				sb.append("downloadfile");
			}
			sb.append("\"");
		}
		headers.put("Content-Disposition", sb.toString());
	}
	
	/**
	 * 设置contentType响应头信息,不指定时默认为application/octet-stream,也必须在setFile方法之后调用
	 * @param contentType
	 */
	public void setContentType(String contentType){
		StringBuilder sb = new StringBuilder();
		contentType = null == contentType ? "application/octet-stream"
				: contentType;
		sb.append(contentType);
		sb.append(";");
		headers.put("Content-Type", sb.toString());
		
	}
	/**
	 * 设置下载文件大小
	 * @param size
	 */
	public void setContentLength(long size){
		headers.put("Content-Length", Long.toString(size));
	}
	/**
	 * 设置文件编码
	 * @param charset
	 */
	public void setCharset(Charset charset){
		this.charset = charset;
		String contentType = ConvertUtil.convert(String.class, headers.get("Content-Type"), "");
		contentType += "charset="+charset.name()+";";
		headers.put("Content-Type", contentType);
	}

    DownloadHttpMessageConverter.java

 

public class DownloadHttpMessageConverter extends
		AbstractHttpMessageConverter<DownloadHelper> {

	@Override
	protected DownloadHelper readInternal(Class<? extends DownloadHelper> arg0,
			HttpInputMessage arg1) throws IOException,
			HttpMessageNotReadableException {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean canRead(Class<?> clazz, MediaType mediaType) {
		return false;
	}

	@Override
	public boolean canWrite(Class<?> clazz, MediaType mediaType) {
		return DownloadHelper.class.equals(clazz);
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		throw new UnsupportedOperationException();
	}

	@Override
	protected void writeInternal(DownloadHelper downFile, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		overrideHeader(outputMessage.getHeaders(), downFile.getHeaders());
		File f = downFile.getFile();
		if(f!=null){
			FileCopyUtils.copy(new FileInputStream(f), outputMessage.getBody());
			if(downFile.isClearFile()){
				f.delete();
			}
		}else{
			FileCopyUtils.copy(downFile.getContent(),new OutputStreamWriter(outputMessage.getBody(),downFile.getCharset()));
		}
	}
	
	private void overrideHeader(HttpHeaders headers,Map<String,String> map){
		for(Map.Entry<String, String> entry : map.entrySet()){
			String key = entry.getKey();
			String value = entry.getValue();
			if(headers.containsKey(key)&&value!=null){
				headers.remove(key);
			}
			headers.add(key, value);
		}
	}

}

 

    springmvc配置文件

 

<mvc:message-converters>
  	<bean class="xg.DownloadHttpMessageConverter" />
 </mvc:message-converters>

 

    调用

 

@RequestMapping("/download")
@ResponseBody
public DownloadHelper download(){
	DownloadHelper dh = new DownloadHelper();
	//下载具体文件
	dh.setFile(new File("c:/a.txt"));
	//下载文本字符串如下
	//dh.setContent("aaaaaaaaaaaa", Charset.forName("UTF-8"));
	//指定下载文件名
	dh.setFileName("下载名");
	return dh;
}

 

 

 

分享到:
评论
2 楼 warlock123 2014-08-06  
Charset charset = FileUtil.getFileEncoding(file);
FileUtil类无此方法;
String contentType = ConvertUtil.convert(String.class, headers.get("Content-Type"), "");
ConvertUtil 自定义的类? 还是哪个包下的?
1 楼 lsliliang 2012-07-20  
sunyard
不是数码科技吧

相关推荐

Global site tag (gtag.js) - Google Analytics