Case (web development): Download

Download file

The client browser to download files from the server. In fact, the hyperlink address is connected to a server-side file path
there is a problem: the browser can identify files, such as pictures, video, audio, pdf, txt, etc., will be opened directly.
Solution: write server-side code that tells the browser what type of time regardless of the file, do not let the browser open, allow the browser to open an attachment, direct download.

The following code is set up in response to head: guidance server browser, the file as an attachment to download

                           内容描述            附件
 response.setHeader("Content-Disposition","attachment;filename=文件名");

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--
        超链接:文件下载
        连接的路径就是服务器文件的地址
    -->
    <a href="/web03/download/a.flv">a.flv</a><br/>
    <a href="/web03/download/a.jpg">a.jpg</a><br/>
    <a href="/web03/download/a.mp3">a.mp3</a><br/>
    <a href="/web03/download/a.mp4">a.mp4</a><br/>
    <a href="/web03/download/a.txt">a.txt</a><br/>
    <a href="/web03/download/a.zip">a.zip</a><br/>
    <a href="/web03/download/a.pdf">a.pdf</a><br/>
    <hr/>
    <!--
        连接的地址,不在是文件的地址,连接某一个Servlet
    -->
    <a href="/web03/download">a.jpg</a><br/>

    <!--
        http://localhost:8080/web03/download.html?a=%E4%BD%A0%E5%A5%BD#
    -->
    <form action="#" method="get">
        <input type="text" name="a"/><input type="submit"/>
    </form>
</body>
</html>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /*
     * 编写程序,通知浏览器请你下载,不要打开
     * 指导浏览器干什么,响应头
     * 浏览器下载是HTTP协议规定
     */

    String agent = request.getHeader("User-Agent");
    String filename="美女.jpg";
    if (agent.contains("MSIE")) {
        // IE浏览器
        filename = URLEncoder.encode(filename, "utf-8");
        filename = filename.replace("+", " ");
    } else if (agent.contains("Firefox")) {
        // 火狐浏览器
        BASE64Encoder base64Encoder = new BASE64Encoder();
        filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
    } else {
        // 其它浏览器
        filename = URLEncoder.encode(filename, "utf-8");
    }
    //Content-Disposition 内容描述		 	 attachment 附件
    response.setHeader("Content-Disposition","attachment;filename="+filename);
    String aFile = getServletContext().getRealPath("download/a.jpg");
    FileInputStream fis = new FileInputStream(aFile);
    OutputStream out = response.getOutputStream();
    int len = 0;
    byte[] bytes = new byte[1024];
    while ((len = fis.read(bytes))!=-1){
        out.write(bytes,0,len);
    }
    fis.close();
}

Guess you like

Origin blog.csdn.net/qq_45083975/article/details/92627481