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();
}
}
}
}
}
}
Java 文件预览和下载
最新推荐文章于 2025-05-23 11:46:06 发布