基于servlet的文件

    添加时间:2013-5-10 点击量:
     




    package com.future.zfs.util;
    

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    @SuppressWarnings(
    serial
    public class FileDownLoadServlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    String path
    =request.getParameter(filename);
    path
    =new String(path.getBytes(ISO-8859-1),utf-8);
    download(path,request,response);
    }

    @SuppressWarnings(
    deprecation
    public HttpServletResponse download(String path,HttpServletRequest request, HttpServletResponse response) {
    try {
    // path是指欲的文件的路径。
    File file = new File(request.getRealPath(/)+/+path);
    // 取得文件名。
    String filename = file.getName();
    // 取得文件的后缀名。
    //String ext = filename.substring(filename.lastIndexOf(.) + 1).toUpperCase();

    // 以流的情势文件。
    InputStream fis = new BufferedInputStream(new FileInputStream(file));
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    // 清空response
    response.reset();
    // 设置response的Header
    response.addHeader(Content-Disposition, attachment;filename= + new String(filename.getBytes(utf-8),ISO-8859-1));
    response.addHeader(
    Content-Length, + file.length());
    OutputStream toClient
    = new BufferedOutputStream(response.getOutputStream());
    response.setContentType(
    application/octet-stream);
    toClient.write(buffer);
    toClient.flush();
    toClient.close();
    }
    catch (IOException ex) {
    ex.printStackTrace();
    }
    return response;
    }
    }





    web.xml



    1 <servlet>
    
    2 <servlet-name>fileDownLoadServlet</servlet-name>
    3 <servlet-class>com.future.zfs.util.FileDownLoadServlet</servlet-class>
    4 </servlet>
    5 <servlet-mapping>
    6 <servlet-name>fileDownLoadServlet</servlet-name>
    7 <url-pattern>/fileDownLoadServlet</url-pattern>
    8 </servlet-mapping>
    9 </servlet>



    1 <a href=fileDownLoadServlet?filename=通信录.xls>哈哈,测试文件</a>


    本文转自互联网,有如侵权,请及时与我接洽 huayalong415@163.com



     


    无论对感情还是对生活,“只要甜不要苦”都是任性而孩子气的,因为我们也不完美,我们也会伤害人。正因为我们都不完美,也因为生活从不是事事如意,所以对这些“瑕疵”的收纳才让我们对生活、对他人的爱变得日益真实而具体。—— 汪冰《世界再亏欠你,也要敢于拥抱幸福》
    分享到: