文件下载

文件下载

Jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>download</title>
</head>
<body>
    <a href="/DownLoadServlet?name=test">test.jpg</a>
    <a href="/DownLoadServlet?name=ceshi">ceshi.txt</a>

</body>
</html>

Servlet:

package com.wildfire.servlet.upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name=req.getParameter("name");
        String fileName="";
        switch (name){
            case "test":
                fileName="test.jpg";
                break;
            case "ceshi":
                fileName="ceshi.txt";
                break;
        }

        //设置响应模式
        resp.setContentType("application/x-msdownload");
        //设置下载之后的文件名
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);
        //获取输出流
        OutputStream outputStream=resp.getOutputStream();
        String path=req.getServletContext().getRealPath("file/"+fileName);
        InputStream inputStream=new FileInputStream(path);
        int temp=0;
        while((temp=inputStream.read())!=-1){
            outputStream.write(temp);
        }
        //关闭输入输出流
        inputStream.close();
        outputStream.close();
    }
}

使用IDEA的时候要注意,在WEB-INF下创建file目录,将图片和文件粘贴到该目录下,然后使用工具栏Build--》Rebuild Project,否则可能无法同步到out下。

posted @ 2020-11-16 20:26  Mr_WildFire  阅读(73)  评论(0编辑  收藏  举报