Servlet文件下载

本文详细介绍了如何使用Java Servlet实现文件下载功能,并正确设置MIME类型,确保浏览器能够正确识别和显示文件类型。通过实例代码演示了获取参数、构造完整路径、读取文件、设置响应头、内容类型以及输出文件到客户端的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class DownloadServlet extends HttpServlet {
    private String contentType = "application/x-msdownload";//也可以是文件的mime
    private String enc = "utf-8";
    private String fileRoot = "d:/";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filepath = request.getParameter("filepath");
        String fullFilePath = fileRoot + filepath;
        /*读取文件*/
        File file = new File(fullFilePath);
        /*如果文件存在*/
        if (file.exists()) {
            String filename = URLEncoder.encode(file.getName(), enc);
            response.reset();
            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            int fileLength = (int) file.length();
            response.setContentLength(fileLength);
            /*如果文件长度大于0*/
            if (fileLength != 0) {
                /*创建输入流*/
                InputStream inStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                /*创建输出流*/
                ServletOutputStream servletOS = response.getOutputStream();
                int readLength;
                while (((readLength = inStream.read(buf)) != -1)) {
                    servletOS.write(buf, 0, readLength);
                }
                inStream.close();
                servletOS.flush();
                servletOS.close();
            }
        }
    }

http://www.blogjava.net/mstar/archive/2005/10/27/17113.html

response.setContentType 对应的文件类型
image/bmp--BMP
image/gif--GIF
image/jpeg--JPEG
image/tiff--TIFF
image/x-dcx--DCX
image/x-pcx--PCX
text/html--HTML
text/plain--TXT
text/xml--XML
application/afp--AFP
application/pdf--PDF
application/rtf--RTF
application/msword--MSWORD
application/vnd.ms-excel--MSEXCEL
application/vnd.ms-powerpoint--MSPOWERPOINT
application/wordperfect5.1--WORDPERFECT
application/vnd.lotus-wordpro--WORDPRO
application/vnd.visio--VISIO
application/vnd.framemaker--FRAMEMAKER
application/vnd.lotus-1-2-3--LOTUS123


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值