兼容IE和Firefox的附件讀取和下載
效果(Firefox3.0)

1.獲取XML數據
數據是這樣獲取的:
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.daijia.soft.hospital.struts.action;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.daijia.soft.hospital.struts.form.DataMapForm;
import com.daijia.soft.hospital.vo.AttachVo;
/**
* MyEclipse Struts Creation date: 06-28-2008
*
* XDoclet definition:
*
* @struts.action path="/attachAction" name="dataMapForm" parameter="method"
* scope="request" validate="true"
*/
public class AttachAction extends BaseAction {
/*
* Generated Methods
*/
/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward queryByProtectId(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DataMapForm dataMapForm = (DataMapForm) form;// TODO Auto-generated
// method stub
response.setContentType("text/xml;charset=utf-8");// 返回XML類型數據
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);
List<AttachVo> list = this.getHospitalService().getAttachsByProtectId(
dataMapForm.getInt("pid"));
StringBuffer xml = new StringBuffer("<attachs>");
for(AttachVo a : list){
xml.append("<attach old-file-name=""")
.append(a.getAoldname()).append(""" ")
.append("aid=""").append(a.getAid()).append(""" ")
.append("size=""").append(a.getAfilesize()).append(""" ")
.append("date=""").append(a.getAdatetime().toLocaleString()).append("""");
xml.append("></attach>");
}
xml.append("</attachs>");
if(logger.isDebugEnabled()){
logger.debug("附件:" + xml.toString());
}
PrintWriter out = response.getWriter();
out.println(xml.toString());
return null;
}
}
2.通過javascript顯示文件下載列表
下載列表是這樣生成的:
<script type="text/javascript">
<!--
var xmlhttp;
function displayAttach(pid, s){
//alert(s.offsetLeft);
var old = document.getElementById("divid");
if(old != null){
document.body.removeChild(old); //先刪除附件層
}
var div = document.createElement("div");
var w = 400; //DIV的寬度
//獲取s左邊距和上邊距
var olds = s;
var x = olds.offsetLeft;
var y = olds.offsetTop;
while(olds = olds.offsetParent){
x += olds.offsetLeft;
y += olds.offsetTop;
}
x = x - w; //往左邊錯開w像素
div.id = "divid";
div.style.position = "absolute";
div.style.backgroundColor = "white";
div.style.left = x;
div.style.top = y;
div.style.width = w;
div.className = "tdStyle3";
var table = document.createElement("table");
table.className = "tdStyle3";
table.style.width = "100%";
table.style.borderLeftColor = "blue";
table.style.borderLeftStyle = "solid";
table.style.borderLeftWidth = 1;
table.style.borderRightColor = "blue";
table.style.borderRightStyle = "solid";
table.style.borderRightWidth = 1;
table.style.borderTopColor = "blue";
table.style.borderTopStyle = "solid";
table.style.borderTopWidth = 1;
table.style.borderBottomColor = "blue";
table.style.borderBottomStyle = "solid";
table.style.borderBottomWidth = 1;
var tr = table.insertRow(0);
var titles = new Array("文件名", "文件大小", "上傳日期");
for(var i = 0; i < titles.length; i ++){
var td1 = tr.insertCell(i);
if(i == 2){
td1.style.textAlign = "right";
var closea = document.createElement("a");
closea.innerHTML = "×";
closea.style.fontWeight = "bold";
closea.style.cursor = "pointer";
closea.onclick = function(){
var old2 = document.getElementById("divid");
if(old2 != null){
document.body.removeChild(old2); //先刪除附件層
}
};
td1.appendChild(closea);
}
}
var tr = table.insertRow(1);
for(var i = 0; i < titles.length; i ++){
var td1 = tr.insertCell(i);
td1.innerHTML = titles[i];
td1.style.fontWeight = "bold";
}
//通過ajax得到附件數據
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType("text/xml");
}
}else if(window.ActiveXObject){
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("get", "attach.do?method=queryByProtectId&dataMap(pid)=" + pid);
xmlhttp.setRequestHeader("cache-control", "no-cache");
xmlhttp.send(null);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
var j = 0;
var xml = xmlhttp.responseXML;
var root = xml.documentElement;
var childs = root.childNodes;
if(childs.length == 0){
var trj = table.insertRow(2);
var tdj0 = trj.insertCell(0);
tdj0.innerHTML = "嘿嘿,沒有附件";
}else{
for(j = 0; j < childs.length; j ++){
var trj = table.insertRow(j + 2); //在firefox中,添加新行時必須加行索引參數
var tdj0 = trj.insertCell(0);//在firefox中,添加新行時必須加列索引參數
var a = document.createElement("a");
a.innerHTML = childs.item(j).getAttribute("old-file-name");
a.href = "download.do?dataMap(aid)=" + childs.item(j).getAttribute("aid");
tdj0.appendChild(a);
var tdj1 = trj.insertCell(1);
tdj1.innerHTML = childs.item(j).getAttribute("size");
var tdj2 = trj.insertCell(2);
tdj2.innerHTML = childs.item(j).getAttribute("date");
}
}
}
}
};
div.appendChild(table);
document.body.appendChild(div);
}
//-->
</script>
3.下載選擇的文件(使用Struts1.2.6自帶的下載Action實現)
文件是這樣下載的:
package com.daijia.soft.hospital.struts.action;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import com.daijia.soft.hospital.service.IHospitalService;
import com.daijia.soft.hospital.struts.form.DataMapForm;
import com.daijia.soft.hospital.vo.AttachVo;
public class DownFileAction extends DownloadAction {
protected static Logger logger = Logger.getLogger("action");
private IHospitalService hospitalService;
public void setHospitalService(IHospitalService hospitalService) {
this.hospitalService = hospitalService;
}
public IHospitalService getHospitalService() {
return hospitalService;
}
@Override
protected StreamInfo getStreamInfo(ActionMapping arg0, ActionForm form,
HttpServletRequest arg2, HttpServletResponse response) throws Exception {
DataMapForm dataMapForm = (DataMapForm) form;
AttachVo vo = hospitalService.getRealFileName(dataMapForm.getInt("aid"));
response.reset();
//attachment:下載
//inline:在瀏覽器中顯示
response.setHeader("Content-disposition", "attachment;filename=" + new String(vo.getAoldname().getBytes(), "iso-8859-1"));// 設置文件名稱
//ResourceStreamInfo rsi = new ResourceStreamInfo("application/x-msdownload", this.getServlet().getServletContext(), "smtp.JPG");
FileStreamInfo rsi = new FileStreamInfo("application/x-msdownload", new File(vo.getAnewname()));
return rsi;
}
}
1.獲取XML數據
數據是這樣獲取的:
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.daijia.soft.hospital.struts.action;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.daijia.soft.hospital.struts.form.DataMapForm;
import com.daijia.soft.hospital.vo.AttachVo;
/**
* MyEclipse Struts Creation date: 06-28-2008
*
* XDoclet definition:
*
* @struts.action path="/attachAction" name="dataMapForm" parameter="method"
* scope="request" validate="true"
*/
public class AttachAction extends BaseAction {
/*
* Generated Methods
*/
/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward queryByProtectId(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DataMapForm dataMapForm = (DataMapForm) form;// TODO Auto-generated
// method stub
response.setContentType("text/xml;charset=utf-8");// 返回XML類型數據
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);
List<AttachVo> list = this.getHospitalService().getAttachsByProtectId(
dataMapForm.getInt("pid"));
StringBuffer xml = new StringBuffer("<attachs>");
for(AttachVo a : list){
xml.append("<attach old-file-name=""")
.append(a.getAoldname()).append(""" ")
.append("aid=""").append(a.getAid()).append(""" ")
.append("size=""").append(a.getAfilesize()).append(""" ")
.append("date=""").append(a.getAdatetime().toLocaleString()).append("""");
xml.append("></attach>");
}
xml.append("</attachs>");
if(logger.isDebugEnabled()){
logger.debug("附件:" + xml.toString());
}
PrintWriter out = response.getWriter();
out.println(xml.toString());
return null;
}
}
2.通過javascript顯示文件下載列表
下載列表是這樣生成的:
<script type="text/javascript">
<!--
var xmlhttp;
function displayAttach(pid, s){
//alert(s.offsetLeft);
var old = document.getElementById("divid");
if(old != null){
document.body.removeChild(old); //先刪除附件層
}
var div = document.createElement("div");
var w = 400; //DIV的寬度
//獲取s左邊距和上邊距
var olds = s;
var x = olds.offsetLeft;
var y = olds.offsetTop;
while(olds = olds.offsetParent){
x += olds.offsetLeft;
y += olds.offsetTop;
}
x = x - w; //往左邊錯開w像素
div.id = "divid";
div.style.position = "absolute";
div.style.backgroundColor = "white";
div.style.left = x;
div.style.top = y;
div.style.width = w;
div.className = "tdStyle3";
var table = document.createElement("table");
table.className = "tdStyle3";
table.style.width = "100%";
table.style.borderLeftColor = "blue";
table.style.borderLeftStyle = "solid";
table.style.borderLeftWidth = 1;
table.style.borderRightColor = "blue";
table.style.borderRightStyle = "solid";
table.style.borderRightWidth = 1;
table.style.borderTopColor = "blue";
table.style.borderTopStyle = "solid";
table.style.borderTopWidth = 1;
table.style.borderBottomColor = "blue";
table.style.borderBottomStyle = "solid";
table.style.borderBottomWidth = 1;
var tr = table.insertRow(0);
var titles = new Array("文件名", "文件大小", "上傳日期");
for(var i = 0; i < titles.length; i ++){
var td1 = tr.insertCell(i);
if(i == 2){
td1.style.textAlign = "right";
var closea = document.createElement("a");
closea.innerHTML = "×";
closea.style.fontWeight = "bold";
closea.style.cursor = "pointer";
closea.onclick = function(){
var old2 = document.getElementById("divid");
if(old2 != null){
document.body.removeChild(old2); //先刪除附件層
}
};
td1.appendChild(closea);
}
}
var tr = table.insertRow(1);
for(var i = 0; i < titles.length; i ++){
var td1 = tr.insertCell(i);
td1.innerHTML = titles[i];
td1.style.fontWeight = "bold";
}
//通過ajax得到附件數據
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType("text/xml");
}
}else if(window.ActiveXObject){
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("get", "attach.do?method=queryByProtectId&dataMap(pid)=" + pid);
xmlhttp.setRequestHeader("cache-control", "no-cache");
xmlhttp.send(null);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
var j = 0;
var xml = xmlhttp.responseXML;
var root = xml.documentElement;
var childs = root.childNodes;
if(childs.length == 0){
var trj = table.insertRow(2);
var tdj0 = trj.insertCell(0);
tdj0.innerHTML = "嘿嘿,沒有附件";
}else{
for(j = 0; j < childs.length; j ++){
var trj = table.insertRow(j + 2); //在firefox中,添加新行時必須加行索引參數
var tdj0 = trj.insertCell(0);//在firefox中,添加新行時必須加列索引參數
var a = document.createElement("a");
a.innerHTML = childs.item(j).getAttribute("old-file-name");
a.href = "download.do?dataMap(aid)=" + childs.item(j).getAttribute("aid");
tdj0.appendChild(a);
var tdj1 = trj.insertCell(1);
tdj1.innerHTML = childs.item(j).getAttribute("size");
var tdj2 = trj.insertCell(2);
tdj2.innerHTML = childs.item(j).getAttribute("date");
}
}
}
}
};
div.appendChild(table);
document.body.appendChild(div);
}
//-->
</script>
3.下載選擇的文件(使用Struts1.2.6自帶的下載Action實現)
文件是這樣下載的:
package com.daijia.soft.hospital.struts.action;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import com.daijia.soft.hospital.service.IHospitalService;
import com.daijia.soft.hospital.struts.form.DataMapForm;
import com.daijia.soft.hospital.vo.AttachVo;
public class DownFileAction extends DownloadAction {
protected static Logger logger = Logger.getLogger("action");
private IHospitalService hospitalService;
public void setHospitalService(IHospitalService hospitalService) {
this.hospitalService = hospitalService;
}
public IHospitalService getHospitalService() {
return hospitalService;
}
@Override
protected StreamInfo getStreamInfo(ActionMapping arg0, ActionForm form,
HttpServletRequest arg2, HttpServletResponse response) throws Exception {
DataMapForm dataMapForm = (DataMapForm) form;
AttachVo vo = hospitalService.getRealFileName(dataMapForm.getInt("aid"));
response.reset();
//attachment:下載
//inline:在瀏覽器中顯示
response.setHeader("Content-disposition", "attachment;filename=" + new String(vo.getAoldname().getBytes(), "iso-8859-1"));// 設置文件名稱
//ResourceStreamInfo rsi = new ResourceStreamInfo("application/x-msdownload", this.getServlet().getServletContext(), "smtp.JPG");
FileStreamInfo rsi = new FileStreamInfo("application/x-msdownload", new File(vo.getAnewname()));
return rsi;
}
}