欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

下载文件Utils

程序员文章站 2022-07-15 09:07:09
...
package com.cplatform.util.io;

import org.apache.commons.logging.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import com.cplatform.util.business.ParamComm;

public class DownFile extends HttpServlet {
    private static org.apache.commons.logging.Log log = LogFactory.getLog(DownFile.class);
    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 doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {

        String fileName = request.getParameter("fileName"); //取得文件名,包括后辍名,可用File类的getName()方法获得
        String filePath = request.getParameter("filePath"); //取得文件路径,服务器端点的绝对路径,如:E:\jsp\。可用File类的getAbsolutePath()方法获得
        String saveName = request.getParameter("saveName"); //文件保存在本地的名字


        if (log.isDebugEnabled()) {
            log.debug("Acquire parameters:");
            log.debug("File Name: " + fileName);
            log.debug("File Path: " + filePath);
            log.debug("Save Name: " + saveName);
        }

        if (filePath!=null) {
            String temp;
            if (System.getProperty("file.separator").equals("/")) {
                temp = "/";
            } else if( filePath.lastIndexOf("/")>0 ){
                temp = "/";
            } else {
                temp = "\\";
            }
            if (!filePath.endsWith(temp)) {
                int position = filePath.lastIndexOf(temp);
                fileName = filePath.substring(position+1);
                filePath = filePath.substring(0,position+1);

                if (log.isDebugEnabled()) {
                    log.debug("Split file path parameter into file path (" +
                            filePath + ") and file name (" + fileName + ").");
                }
            }

            //~ 转码的问题已由filter统一处理
            // fileName = Chinese.fromPage(fileName);

            if (saveName==null || saveName.equals("")) {
                saveName = fileName;
            }

            //~ 转码的问题已由filter统一处理
            // saveName = Chinese.toDatabase(saveName);

            File file = new File(filePath+fileName);

            if (file.exists()) {
                response.reset();

                response.setContentType("*/*;charset=gbk"); //这里设成 */* 是因为可以让浏览器根据文件的后辍来自动选择一种文件类型
              
                response.setHeader("Content-disposition",
                        "attachment; filename=" + new String(saveName.getBytes("GBK"),"iso8859-1")); //在下载文件名里显示服务器端的文件名

                int size = (int) file.length();

                java.io.OutputStream os = response.getOutputStream();
                java.io.FileInputStream fis = new java.io.FileInputStream(filePath +
                        fileName);

                int len = 1024;

                if (size > (1024 * 1024) && size < (1024 * 1024 * 10)) {
                    len = 10240;
                }
                else if (size > (1024 * 1024 * 10)) {
                    len = 102400;
                }

                byte[] b = new byte[len];
                int i;

                try {
                    while ( (i = fis.read(b)) > 0) {
                        os.write(b, 0, i);
                    }

                } catch (IOException e) {
                    if (log.isInfoEnabled()) {
                        log.info("下载文件出错:" + e.getMessage());
                    }
                } finally {

                    try { fis.close(); } catch (IOException e) { }
                    try {
                        os.flush();
                        os.close();
                    } catch (IOException e) { }
                }

            } else {
                response.setContentType(CONTENT_TYPE);
                PrintWriter out = response.getWriter();
                out.println("<html>");
                out.println("<head><title>FileDown</title></head>");
                out.println("<body bgcolor=\"#ffffff\">");
                out.println(
                        "<script>alert('文件不存在,下载失败!');window.close();</script>");
                out.println("</body></html>");
            }
//        file.delete();//下载后删除源文件
        } else {
            response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title>FileDown</title></head>");
            out.println("<body bgcolor=\"#ffffff\">");
            out.println(
                    "<script>alert('文件参数不全,下载失败!');window.close();</script>");
            out.println("</body></html>");
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {}

}