ServletContext_功能_获取文件服务器路径与案例_文件下载_分析

ServletContext_功能_获取文件服务器路径

    获取文件的真实(服务器)路径

    1.方法:String  getRealPath(String  path)

      

 

 

 

      

       服务器真实路径

      

 

 

       工作台打印出来的真实路径  

      

 

 

 

 

复制代码
package qh.xueqiang.servletcontext;

import javax.servlet.ServletContext;
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.File;
import java.io.IOException;

@WebServlet("/contextDemo05")
public class ContextDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*

                    ServletContext功能
                      1.获取MIME类型:    
               
             2.域对象:共享数据  

             3.获取文件的真实(服务器)路径   
         */


            //2.通过HttpSevlert获取
        ServletContext context = this.getServletContext();

            //获取文件的服务器路径
        String realPath = context.getRealPath("/b.txt"); //web目录下资源访问
        System.out.println(realPath);
       // File file = new File(realPath);

        String realPath1 = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源文件
        System.out.println(realPath1);

        String realPath2 = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
        System.out.println(realPath2);


    }
}
复制代码

 

 

 

案例_文件下载_分析

    

文件下载需求:
    1. 页面显示超链接
    2. 点击超链接后弹出下载提示框
    3. 完成图片文件下载

文件下载分析:

    1.超链接指向的资源如果能够被浏览器解析,则浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求

    2.任何资源都必须弹出下载提示框

    3.使用响应头设置资源的打开方式:

        content-disposition:attachment;filenname = xxx

文件下载步骤:

    1. 定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename

    2. 定义Servlet
        1. 获取文件名称
        2. 使用字节输入流加载文件进内存
        3. 指定response的响应头: content-disposition:attachment;filename=xxx
        4. 将数据写出到response输出流

 

    

posted @   zj勇敢飞,xx永相随  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示