会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132475个问题
Python 全系列/第一阶段:Python入门/控制语句 30257楼
Python 全系列/第十六阶段:数据结构与算法/算法与数据结构(旧) 30258楼
JAVA 全系列/第十三阶段:高性能数据处理、NoSQL、分库分表/Redis 30266楼

我的项目输出目录找不到图片,不知道配置是哪里出了问题

666.png


888.png



代码如下:

package com.bjsxt.servletDemo;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 文件下载
 */
public class DownFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取ServletContext对象
        ServletContext servletContext = this.getServletContext();

        //路径转换
        String realPath = servletContext.getRealPath("image/美女.jpg");
        System.out.println(realPath);
        //读文件
        File file = new File(realPath);
        FileInputStream fis = new FileInputStream(file);
        byte[] buff = new byte[fis.available()];
        fis.read(buff);

        //在响应中添加附加信息
        resp.addHeader("Content-Disposition","attachment; filename="+new String(file.getName().getBytes("gbk"),"iso-8859-1"));
        OutputStream os = resp.getOutputStream();
        os.write(buff);
        os.flush();
        os.close();



    }
}


JAVA 全系列/第五阶段:JavaWeb开发/Servlet技术详解(旧) 30267楼
JAVA 全系列/第五阶段:JavaWeb开发/JSP技术详解(旧) 30268楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637