实现功能
知识库系统中存在一个附件就是一个知识,当全文搜索到这个附件知识的时候需要能在线查看这个知识也就是附件里的文章内容。(如果不是pdf格式的文档,我们这边是先将不同格式的附件转成PDF格式)
实现代码
本项目中我在jsp页面中用了embed 标签
<embed :src="file/open.action" type="application/pdf" width="100%" height="100%">
标签里src的file/open.action里面主要是读写附件文件的IO流的一个action。直接上代码:
package com.ssm.controlle;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author chenjida
* @create 2019-09-05
*/
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/openAttach")
@ResponseBody
public void openAttach(HttpServletResponse response) {
FileInputStream fIn = null;
OutputStream out = null;
try {
response.addHeader("Content-Disposition",
"filename=\"" + new String("D:\\7c8f4802-a6aa-4517-b7db-a752987fcf6c.pdf".getBytes("gb2312"), "ISO8859-1") + "\"");
response.setHeader("Content-Type", "application/pdf");
File file = new File("D:\\7c8f4802-a6aa-4517-b7db-a752987fcf6c.pdf");
if(!file.exists()){
return;
}
// 读取下载文件
fIn = new FileInputStream(file);
// 输出流
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fIn.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
IOUtils.closeQuietly(fIn);
IOUtils.closeQuietly(out);
}
}
}