我现在用smartUpload把文件上传到一个文件夹里,文件名存在数据库中,在下载页面有什么好的办法?

解决方案 »

  1.   

    难道要写个servlet?有代码贴阿,哥哥!
      

  2.   

    你要有一个文件下载程序,并且此程序中contentType设为application/octet-stream
      

  3.   

    下载
    -------------
      
      <%
      // 得到文件名字和路径
      String filename = "test.gif";
      String filepath = "D:\\";
      
      // 设置响应头和下载保存的文件名
      response.setContentType("APPLICATION/OCTET-STREAM");
      response.setHeader("Content-Disposition",
      "attachment; filename=\"" + filename + "\"");
     
      // 打开指定文件的流信息
      java.io.FileInputStream fileInputStream =
       new java.io.FileInputStream(filepath + filename);
       
      // 写出流信息
      int i;
      while ((i=fileInputStream.read()) != -1) {
       out.write(i);
      }
      fileInputStream.close();
      out.close();
     %>
     
     值得注意的是:在你要下载的文件内容里,除了文件的内容之外,不应该再附加有其它任何的字符,包括空格和回车换行符。我们有时在编写代码的时候,为了使代码清晰可读,往往会添加一些空格、制表符或者回车换行符,这样虽然看起来比较清晰,但有时可能会得不到正确的结果。比如:
     <%@ page import="java.io.*"
     %>  <jsp:useBean id="MyBeanFromMengxianhui" scope="page"
     class="com.Mengxianhui.DownloadBean" />
     应该写成这样:
     <%@ page import="java.io.*"
     %><jsp:useBean id="MyBeanFromMengxianhui" scope="page"
     class="com.Mengxianhui.DownloadBean" />
      

  4.   

    一共五个类,分别如下,package com.netec.util.download;/**
     * <p>Title:download exception </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2004</p>
     * <p>Company: </p>
     * @author not attributable
     * @version 1.0
     */public class DowLoadException extends Exception {  public DowLoadException() {
      }  public DowLoadException(String p0) {
        super(p0);
      }  public DowLoadException(Throwable p0) {
        super(p0);
      }  public DowLoadException(String p0, Throwable p1) {
        super(p0, p1);
      }
    }
    package com.netec.util.download;import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.net.URLEncoder;
    import java.io.UnsupportedEncodingException;
    import java.io.FileInputStream;
    import java.io.*;/**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2004</p>
     * <p>Company: </p>
     * @author not attributable
     * @version 1.0
     */public class DownLoad {
      private DownLoad() {
      }
      public static void donwload(
          HttpServletRequest request,
          HttpServletResponse response,
          String src_fname,
          String dst_fname
          ) throws DowLoadException {
          int buffSize=1024*10;//size of buffer for read file
          //try {
            //Translates the file's name into application/x-www-form-urlencoded format
           // dst_fname = URLEncoder.encode(dst_fname, "UTF-8");
          //}
         // catch (UnsupportedEncodingException ex) {
          //  throw new DowLoadException("error to encode the file's name ",ex);
          //}
          response.setContentType("application/octet-stream; charset=GBK");
          response.setHeader("Content-disposition", "attachment; filename=\"" + dst_fname + "\"");
          FileInputStream fis = null;
          try {
            fis = new FileInputStream(src_fname);
          }
          catch (FileNotFoundException ex) {
            throw new DowLoadException("source file is not found",ex);
          }
          BufferedInputStream buffIn=new BufferedInputStream(fis);      byte[] byteBuff=new byte[buffSize];
          try {
            OutputStream outStream = response.getOutputStream();
            BufferedOutputStream buffOut=new BufferedOutputStream(outStream);
            int validLength=0;
            //carry btye arrary
            while((validLength=buffIn.read(byteBuff))!=-1){
              buffOut.write(byteBuff,0,validLength);
            }
            buffOut.flush();
            buffOut.close();
            buffIn.close();
          }
          catch (IOException ex) {
            throw new DowLoadException("file option error",ex);
          }
      }
    }
      

  5.   

    package com.netec.util.download.servlet;import javax.servlet.*;
    import javax.servlet.http.*;import com.netec.util.RequestNativeProxy;
    import com.netec.util.download.DowLoadException;
    import com.netec.util.download.DownLoad;import java.io.*;
    public class DownLoadServlet extends HttpServlet {
      private static final String CONTENT_TYPE = "text/html; charset=GBK";  //Initialize global variables
      public void init() throws ServletException {
      }  //Process the HTTP Get request
      public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request proxy deal with "iso-8859-1"cord for getParameter method.
        request=new RequestNativeProxy(request);
        /*
        if(!request.getMethod().trim().equalsIgnoreCase("post")){
         throw new ServletException("This request must be \"post\" method. ");
        }*/
        String src_fname = request.getParameter("src_fname");
        String dst_fname = request.getParameter("dst_fname");
        //To get whole source file name
        src_fname=this.getServletContext().getRealPath(src_fname);
        src_fname = src_fname.replace('/',File.separatorChar);
        try {
          DownLoad.donwload(request, response, src_fname, dst_fname);
        }
        catch (DowLoadException ex) {
          //throw new ServletException(ex);
          ex.printStackTrace(System.out);
        }
        return;
      }  //Clean up resources
      public void destroy() {
      }
    }package com.netec.util;
    public class ConversionHtml {    /**
         * (Constructor)
         *  
         */
        private ConversionHtml() {
            super();
        }    public static String StringToHtml(String str) {
            String repStr = str;
            repStr = repStr.replaceAll("\r\n", "<BR>");
            repStr = repStr.replaceAll("\r", "<BR>");
            repStr = repStr.replaceAll("\n", "<BR>");
            repStr = repStr.replaceAll(" ", "&nbsp;");
            return repStr;
        }    public static String HtmlToString(String str) {
            String repStr = str;
            repStr = repStr.replaceAll("<br>|<BR>|<Br>|<bR>|<br/>|<BR/>", "\r\n");
            repStr = repStr.replaceAll("&nbsp;", " ");
            return repStr;
        }
    }
      

  6.   

    package com.netec.util;import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.Principal;
    import java.util.Enumeration;
    import java.util.Locale;
    import java.util.Map;import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    public class RequestNativeProxy implements HttpServletRequest {
    private HttpServletRequest request;   
        public RequestNativeProxy(HttpServletRequest request) {
            super();
            this.request=request;
        }   
        public String getAuthType() {
            return request.getAuthType();
        }  
        public Cookie[] getCookies() {
            return request.getCookies();
        }    
        public long getDateHeader(String arg0) {
            return request.getDateHeader(arg0);
        }    
        public String getHeader(String arg0) {
            return request.getHeader(arg0);
        }    
        public Enumeration getHeaders(String arg0) {
            return request.getHeaders(arg0);
        }   
        public Enumeration getHeaderNames() {
            return request.getHeaderNames();
        }    
        public int getIntHeader(String arg0) {
            return request.getIntHeader(arg0);
        }   
        public String getMethod() {
            return request.getMethod();
        }    
        public String getPathInfo() {
            return request.getPathInfo();
        }   
        public String getPathTranslated() {
            return request.getPathTranslated();
        }   
        public String getContextPath() {
            return request.getContextPath();
        }   
        public String getQueryString() {
            return request.getQueryString();
        }   
        public String getRemoteUser() {
            return request.getRemoteUser();
        }  
        public boolean isUserInRole(String arg0) {
             return request.isUserInRole(arg0);
        }   
        public Principal getUserPrincipal() {
            return request.getUserPrincipal();
        }   
        public String getRequestedSessionId() {
            return request.getRequestedSessionId();
        }   
        public String getRequestURI() {
            return request.getRequestURI();
        }
       
        public StringBuffer getRequestURL() {
            return request.getRequestURL();
        }    
        public String getServletPath() {
            return request.getServletPath();
        }    
        public HttpSession getSession(boolean arg0) {
            return request.getSession(arg0);
        }    
        public HttpSession getSession() {
            return request.getSession();
        }   
        public boolean isRequestedSessionIdValid() {
            return request.isRequestedSessionIdValid();
        }  
        public boolean isRequestedSessionIdFromCookie() {
            return request.isRequestedSessionIdFromCookie();
        }    
        public boolean isRequestedSessionIdFromURL() {
            return request.isRequestedSessionIdFromURL();
        }   
        public boolean isRequestedSessionIdFromUrl() {
            throw new UnsupportedOperationException();
        }   
        public Object getAttribute(String arg0) {
            return request.getAttribute(arg0);
        }    
        public Enumeration getAttributeNames() {
            return request.getAttributeNames();
        }   
        public String getCharacterEncoding() {
            return request.getCharacterEncoding();
        }    
        public void setCharacterEncoding(String arg0)
                throws UnsupportedEncodingException {
            request.setCharacterEncoding(arg0);    }    
        public int getContentLength() {
            return request.getContentLength();
        }    
        public String getContentType() {
            return request.getContentType();
        }    
        public ServletInputStream getInputStream() throws IOException {
            return request.getInputStream();
        }    
        public String getParameter(String arg0) {
            try {
                if(request.getParameter(arg0)!=null) {
                    return new String(request.getParameter(arg0).getBytes("ISO-8859-1"));
                }else {
                    return null;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "null"+e.getMessage();
            }
        }   
        public Enumeration getParameterNames() {
            return request.getParameterNames();
        }    
        public String[] getParameterValues(String arg0) {
            String[] values= request.getParameterValues(arg0);
            for(int i=0;i<values.length;i++) {
                try {
                    if(values[i]!=null) {
                        values[i]=new String(values[i].getBytes("ISO-8859-1"));
                    }else {
                        values[i]=null;
                    }            } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    values[i]="null"+e.getMessage();
                }
            }
            return values;
        }   
        public Map getParameterMap() {
            String newValue;
            String oldValue;
            String name;
            Enumeration names=request.getParameterNames();
            Map parameterMap=request.getParameterMap();
            while(names.hasMoreElements()) {
                name=(String)names.nextElement();
                oldValue=(String)parameterMap.get(name);
                try {
                    if(oldValue!=null) {
                        newValue=new String(oldValue.getBytes("ISO-8859-1"));
                    }else {
                        newValue=null;
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    newValue="null"+e.getMessage();
                }
                parameterMap.put(name,newValue);
            }
            return parameterMap;
        }    
        public String getProtocol() {
            return request.getProtocol();
        }    
        public String getScheme() {
            return request.getScheme();
        }    
        public String getServerName() {
            return request.getServerName();
        }   
        public int getServerPort() {
            return request.getServerPort();
        }    
        public BufferedReader getReader() throws IOException {
            return request.getReader();
        }   
        public String getRemoteAddr() {
            return request.getRemoteAddr();
        }   
        public String getRemoteHost() {
            return request.getRemoteHost();
        }  
        public void setAttribute(String arg0, Object arg1) {
            request.setAttribute(arg0,arg1);
        }   
        public void removeAttribute(String arg0) {
            request.removeAttribute(arg0);    }   
        public Locale getLocale() {
            return request.getLocale();
        }   
        public Enumeration getLocales() {
            return request.getLocales();
        }   
        public boolean isSecure() {
            return request.isSecure();
        }    
        public RequestDispatcher getRequestDispatcher(String arg0) {
            return request.getRequestDispatcher(arg0);
        }   
        public String getRealPath(String arg0) {
            throw new UnsupportedOperationException();
        }    public int getRemotePort() {
            
            throw new UnsupportedOperationException();
        }    
        public String getLocalName() {
            throw new UnsupportedOperationException();
        }    
        public String getLocalAddr() {
            throw new UnsupportedOperationException();
        }    
        public int getLocalPort() {
            throw new UnsupportedOperationException();
        }}
      

  7.   

    <%@page language="java" pageEncoding="GB2312" import="com.jspsmart.upload.*"%><%
    SmartUpload download = new SmartUpload();
    try{
    download.initialize(pageContext);
    download.setContentDisposition(null);
    String filename=request.getParameter("filename");
    String path="/upload/"+filename;
    download.downloadFile("/down/form_txt12.gif");
    }catch(SmartUploadException e){e.printStackTrace();}%>
    我也在这个问题上搞了好久,为了让更多的人不吃这个苦,吗的要这么写!!!!在你得download.jsp中这么写!
      

  8.   

    接昨天
           web.xml 中加如下       <servlet>
    <servlet-name>download</servlet-name>
    <servlet-class>
    com.netec.util.download.servlet.DownLoadServlet
    </servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>download</servlet-name>
    <url-pattern>/download</url-pattern>
    </servlet-mapping>
    jsp页面如下
    <a href="/download?src_fname=XXX.jsp&dst_fname=下载后保存的文件名" />下载</a>