Java 文件预览和下载

package com.souche.json;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@Api(value = "MyTest", description = "测试")
@Controller
public class MyTest {

	
	@ApiOperation(value = "预览",httpMethod="GET")
	@RequestMapping("readAndDownload.do")
	public void readAndDownload(HttpServletResponse res, String params)  {
		InputStream in = null;
		OutputStream out = null;
		String filePaths = "/Users/zhaobin/git/saas_cm_svc/web/config/optimus/properties/***.docx";
		if (filePaths != null) {
			boolean c = new File(filePaths).exists();
			try {
				in = new FileInputStream(filePaths);

				// 设置响应头
				// 设置应用参数
				// 第二步:设置响应的类型
				if ("dwld".equalsIgnoreCase(params)) {
					res.setContentType("application/force-download");

					res.setContentLength(in.available());
				} else {
					res.setContentType("application/pdf");
				}
				String userAgent = request.getHeader("User-Agent").toLowerCase();  
				String fileName="文件名称";
			if (userAgent.contains("msie") || userAgent.contains("trident") ) {  
			    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");  
			} else {  
			    // 非IE浏览器的处理:  
			    fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");  
			}  
			//response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\""); 
				// 第三步:开始文件copy
				out = res.getOutputStream();
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					out.write(b, 0, len);
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值