1.Servlet
package com.ly.jxjhgl.views.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
/**
* 查看培养方案-年级专业信息附件预览
* @author 林诗景
* @date 2018-3-07
*/
public class NjzyServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html;charset=UTF-8";
private static final long serialVersionUID = 1L;
private static int DEFAULT_BUFFER_SIZE = 102400; //10kb
public NjzyServlet() {
super();
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException,
IOException {
ServletContext context = this.getServletContext();
String path =
context.getInitParameter("njzy_path"); //获取web.xml的context-param参数,值为/jwxt/njzy
String filePath = path + File.separator + request.getParameter("name");
File file = new File(filePath);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
PrintWriter pw = null;
if (!file.exists()) {
response.setContentType(CONTENT_TYPE);
pw = response.getWriter();
pw.print("<html>");
pw.print("<head><title>附件丢失</title></head>");
pw.print("<body>");
pw.print("<p>附件丢失,请重新上传或联系管理员。</p>");
pw.print("</body></html>");
pw.close();
return;
}
/*
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") ||
userAgent.contains("Trident")) { //IE内核浏览器
filename = URLEncoder.encode(file.getName(), "UTF-8");
} else { //非IE内核浏览器
filename =
new String(file.getName().getBytes("UTF-8"), "ISO-8859-1");
}
*/
String filename = null;
String contentType = context.getMimeType(file.getName());
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "filename=\"" + filename + "\"");
bis = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
bos = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
IOUtils.copy(bis, bos);
IOUtils.closeQuietly(bis);
IOUtils.closeQuietly(bos);
}
}
2.web.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
<context-param>
<param-name>njzy_path</param-name>
<param-value>/jwxt/njzy</param-value>
</context-param>
<servlet>
<servlet-name>njzyServlet</servlet-name>
<servlet-class>com.ly.jxjhgl.views.servlet.NjzyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>njzyServlet</servlet-name>
<url-pattern>/njzy</url-pattern>
</servlet-mapping>
</web-app>
3.页面和Java代码
页面
<af:popup id="p1" contentDelivery="lazyUncached"
autoCancel="disabled" binding="#{newPyfaBean.richPop}">
<af:dialog type="none" title="附件" id="d32">
<af:panelGroupLayout id="pgl3">
<af:inlineFrame source="#{newPyfaBean.url}"
inlineStyle="height:700px;width:1000px;"
styleClass="AFStretchWidth" shortDesc="预览"
id="if1"/>
</af:panelGroupLayout>
</af:dialog>
</af:popup>
Java代码
package com.ly.jxjhgl.jxjhpyfa.VO.CustomerVO;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.ly.jxjhgl.views.utils.ADFUtils;
import com.ly.jxjhgl.views.utils.JSFUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import oracle.adf.share.ADFContext;
import oracle.adf.share.logging.ADFLogger;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.jbo.Row;
import oracle.jbo.domain.BlobDomain;
import oracle.jbo.server.ViewObjectImpl;
import org.apache.commons.io.IOUtils;
public class NewPyfaBean {
private ADFLogger log = ADFLogger.createADFLogger(NewPyfaBean.class);
private RichPopup richPop;
private static String TYPE_PDF = ".pdf";
public NewPyfaBean() {
}
/**
* 附件预览
* @param actionEvent
*/
public void preview(ActionEvent actionEvent) {
String path = JSFUtils.getInitParameter("njzy_path"); //获取web.xml的context-param参数,值为/jwxt/njzy
File dir = new File(path);
if (dir.exists()) {
this.removeDir(dir); //如果目录存在,则先删除再创建。
}
dir.mkdirs();
ViewObjectImpl vo = (ViewObjectImpl)ADFUtils.findIterator("JxjhPyfaNjzyxxVo1Iterator").getViewObject();
Row row = vo.getCurrentRow();
String wjmc = row.getAttribute("Wjmc") == null ? "" : row.getAttribute("Wjmc").toString(); //文件名称
String filePath = path + File.separator + wjmc;
File file = new File(filePath);
String pdfFilename = wjmc.substring(0, wjmc.lastIndexOf(".")) + TYPE_PDF; //OpenOffice预览文件只支持PDF格式
if (wjmc.endsWith(TYPE_PDF) || wjmc.endsWith(".doc") ||
wjmc.endsWith(".docx") || wjmc.endsWith(".xls") ||
wjmc.endsWith(".xlsx")) {
BlobDomain blob = (BlobDomain)row.getAttribute("Wj"); //数据库BLOB类型字段
try {
OutputStream outputStream = new FileOutputStream(filePath);
IOUtils.copy(blob.getBinaryStream(), outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
OpenOfficeConnection conn = new SocketOpenOfficeConnection("127.0.0.1", 8100);
if (!wjmc.endsWith(TYPE_PDF)) {
File pdfFile = new File(path + File.separator + pdfFilename);
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(conn);
converter.convert(file, pdfFile);
ADFContext.getCurrent().getPageFlowScope().put("wjmc", pdfFilename);
JSFUtils.showPopup(richPop);
}
} else {
JSFUtils.addFacesInformationMessage("预览只支持excel,word,pdf格式的文件。");
return;
}
}
/**
*获取系统的URL
* @return
*/
public String getUrl() {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
Object obj = ec.getRequest();
if (obj instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest)obj;
String path = request.getRequestURL().toString();
path = path.substring(0, path.lastIndexOf("/faces") + 6);
//找到web.xml里的url-pattern值为/njzy对应的Servlet
return path + "/njzy?name=" + ADFContext.getCurrent().getPageFlowScope().get("wjmc");
}
return null;
}
/**
* 删除文件夹下所有文件,递归
* @param directory
* @return
*/
private boolean removeDir(File directory) {
if (directory.isDirectory()) {
String[] fileList = directory.list();
for (String file : fileList) {
boolean flag = removeDir(new File(directory, file));
if (!flag) {
return false;
}
}
}
return directory.delete(); //此时目录为空,可以删除
}
public void setRichPop(RichPopup richPop) {
this.richPop = richPop;
}
public RichPopup getRichPop() {
return richPop;
}
}