会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132837个问题
JAVA 全系列/第一阶段:JAVA 快速入门/面向对象详解和JVM底层内存分析 31786楼
WEB前端全系列/第十八阶段:Vue3知识体系/Vue基础 31787楼
JAVA 全系列/第一阶段:JAVA 快速入门/面向对象详解和JVM底层内存分析 31788楼
Python 全系列/第一阶段:Python入门/编程基本概念 31793楼
JAVA 全系列/第十八阶段:亿级高并发电商项目_架构/编码(旧)/电商:基于FastDFS+Nginx+Kinkeditor实现商品新增 31794楼
Python 全系列/第一阶段:Python入门/序列 31796楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 31797楼

老师,我想追问一下下图的问题,如果还要自己在tomcat的项目文件夹中自己添加image/picture.jpg, 那为什么要在项目文件夹中创建image文件夹?我没在项目中创建image文件夹和图片,还是可以通过/download.do下载文件,如图二。


image.png

image.png

代码:

package com.bjsxt.servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class DownloadFileServlet 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/rickandmortybg.jpg");
        System.out.println(realPath);
        // 读文件
        File file = new File(realPath);
        System.out.println(file.getName());
        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("utf-8"), "iso-8859-1"));

        OutputStream os = resp.getOutputStream();
        os.write(buff);
        os.flush();
        os.close();
    }
}


JAVA 全系列/第五阶段:JavaWeb开发/Servlet技术详解(旧) 31798楼
人工智能/第十四阶段:深度学习-目标检测YOLO(V8正在更新中)实战/YOLOv1详解 31799楼
Python 全系列/第十四阶段:Python 爬虫开发/爬虫基础 31800楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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