下载

来源:互联网 发布:电脑声音增强软件 编辑:程序博客网 时间:2024/04/30 03:24
package cn.huain.servlet;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletDemo04 extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, UnsupportedEncodingException {        //中文命名下载        String path = this.getServletContext().getRealPath("/download/日本妞.jpg");        String filename = path.substring(path.lastIndexOf("\\") + 1);        //设置中文下载头        resp.setHeader("content-disposition", "attachment;filename=" +URLEncoder.encode(filename, "UTF-8"));        InputStream in = null;        OutputStream out = null;        try {            in = new FileInputStream(path);            out = resp.getOutputStream();            byte[] b = new byte[1024];            int len = -1;            while ((len = in.read(b)) != -1) {                out.write(b, 0, len);            }        } catch (IOException e1) {            e1.printStackTrace();        } finally {            if (in != null)                try {                    in.close();                } catch (IOException e) {                    e.printStackTrace();                }            if (out != null)                try {                    out.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }    private void test1(HttpServletResponse resp) {        String path = this.getServletContext().getRealPath("/download/1.jpg");        String filename = path.substring(path.lastIndexOf("\\") + 1);        //设置下载头        resp.setHeader("content-disposition", "attachment;filename=" + filename);        InputStream in = null;        OutputStream out = null;        try {            in = new FileInputStream(path);            out = resp.getOutputStream();            byte[] b = new byte[1024];            int len = -1;            while ((len = in.read(b)) != -1) {                out.write(b, 0, len);            }        } catch (IOException e1) {            e1.printStackTrace();        } finally {            if (in != null)                try {                    in.close();                } catch (IOException e) {                    e.printStackTrace();                }            if (out != null)                try {                    out.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        doGet(req, resp);    }}
0 0
原创粉丝点击