一个Java在线预览和下载的例子

来源:互联网 发布:coc防空数据 编辑:程序博客网 时间:2024/05/16 12:30

     前一段是有一个在线预览的一个需求,本来打算用swf插件,但是由于公司不让用office产品,只能使用其他办法来实现在线预览,我整理了一个小例子,在这里跟大家分享一下。

         第一次写微博有的地方表达的不清楚,请大家见谅哈

(以下是代码)注:前提是浏览器必须有在线预览器的应用,少些ie没有

package com.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
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;


@Controller
public class readAndDownload {

@RequestMapping("readAndDownload.do")
public void readAndDownload(HttpServletResponse res, String params) throws Exception{
InputStream in = null;
OutputStream out = null;
String filePaths = "C:\\Users\\山沟里的程序猿\\Desktop\\pythonwss.pdf";
if(filePaths !=null){
in = new FileInputStream(filePaths);

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

res.setContentLength(in.available());
} else {
res.setContentType("application/pdf");
}
// 第三步:开始文件copy
out = res.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}

}

}

(效果图)---------------------


原创粉丝点击