Java海阔天空

编程是我的生活,但生活不仅仅是编程。

兼容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;
}
}

posted on 2008-07-04 09:29 李赞红 阅读(1537) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2008年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

统计

常用链接

留言簿(12)

随笔档案(28)

相册

技术友情博客

搜索

最新评论

阅读排行榜

评论排行榜