会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 134292个问题
JAVA 全系列/第一阶段:AI驱动的JAVA编程/数组和数据存储 17253楼
Python全系列/第一阶段:AI驱动的Python编程/控制语句 17254楼
Python全系列/第二阶段:Python 深入与提高/异常机制 17257楼
Python全系列/第二阶段:Python 深入与提高/异常机制 17261楼
Python全系列/第一阶段:AI驱动的Python编程/编程基本概念 17262楼

老师我的运行不出来

package FistServet01;
//下载本地文件
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 DownloadFileServlet07 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();
        //路径转换 ServletContext第一个作用相对路径转化为绝对路径
        String realPath = servletContext.getRealPath("image/cat.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;file+"+new String(file.getName().getBytes("gbk"),"iso-8859-1")); //实现文件下载要修改响应头添加附加信息
        OutputStream os = resp.getOutputStream();
        os.write(buff);
        os.flush();
        os.close();
    }
}

image.png

JAVA 全系列/第六阶段:JavaWeb开发/Servlet技术详解(旧) 17263楼
JAVA 全系列/第五阶段:Web全栈开发基础与Vue/Javascript 语言(旧) 17264楼
Python全系列/第十二阶段:Python_Django3框架/Django进阶 17265楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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