只用过DownLoadAction介意楼主看下......代码就懒得发了

解决方案 »

  1.   

    /*
     * Generated by MyEclipse Struts
     * Template path: templates/java/JavaClass.vtl
     */
    package com.zkjy.struts.action;import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;/** 
     * MyEclipse Struts
     * Creation date: 03-28-2008
     * 
     * XDoclet definition:
     * @struts.action
     */
    public class DownloadAction extends Action {
    /*
     * Generated Methods
     */ /** 
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    String filename;
    String path;
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)throws Exception {
    // TODO Auto-generated method stub

    request.setCharacterEncoding("utf-8");
    filename=request.getParameter("filename");
    path = servlet.getServletContext().getRealPath("/fileupload")+"/"+filename;
    downfile(response);
    return mapping.findForward("index");
    }
    public void downfile(HttpServletResponse response) throws IOException{
    String f;
    if(filename!=null)
    {
    File file=new File(path);

    if(!file.exists()) throw new IOException("文件不存在:"+file.getPath());
    else{
    f=toUTF8String(filename);
    response.setContentType("application/x-msdownload");
    response.setContentLength((int)file.length());
    response.setHeader("Content-Disposition", "attachment;filename="+f);
    write(response.getOutputStream());
    }
    }
    }
    public static String toUTF8String(String s){
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<s.length();i++){
    char c=s.charAt(i);
    if(c>=0&&c<=255){
    sb.append(c);
    }
    else{
    byte[] b;
    try{
    b=Character.toString(c).getBytes("UTF-8");
    }catch(Exception e){System.out.println(e);b=new byte[0];}
    for(int j=0;j<b.length;j++){
    int k=b[j];
    if(k<0)
    k+=256;
    sb.append("%"+Integer.toHexString(k).toUpperCase());
    }
    }
    }
    return sb.toString();
    }
    protected void write(OutputStream os) throws IOException {
    FileInputStream fis = new FileInputStream(path);
    BufferedInputStream bis = new BufferedInputStream(fis);
    byte[] s = new byte[1024];
    int i = 0;
    while ((i = bis.read(s)) > 0) {
    os.write(s, 0, i);
    }
    if (os != null) {
    os.flush();
    os.close();
    }
    if (bis != null)
    bis.close();
    if (fis != null)
    fis.close();
    }
    }