jsb和servlet文件下载步骤

2022-11-13 11:02:13 浏览数 (1)

代码语言:javascript复制
package com.example.demo3;

import org.apache.commons.io.IOUtils;

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.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要下载的文件名
        String downloadfilename="a.jpg";
         //读取要下载的文件内容
        ServletContext servletContext=getServletContext();
         //读取输入流的数据,输出客户端
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/"   downloadfilename);
        //读取输入流的全部数据
        String mimeType = servletContext.getMimeType("/file/"   downloadfilename);
        System.out.println("下载的文件类型" mimeType);
        //获取输出流量
        OutputStream outputStream=resp.getOutputStream();
        IOUtils.copy(resourceAsStream,outputStream);
         // 在回传前告诉客户端返回的数据类型
        resp.setContentType(mimeType);
        //Content-Disposition响应头,表示收到的数据怎么处理
        //attachment附件
        // filename下载的文件名
        resp.setHeader("Content-Disposition","attachment;filename");
    }
}

很重要很重要,多敲

0 人点赞