zoukankan      html  css  js  c++  java
  • 文件下载

    package com.bjsxt.servlet;
    
    import org.apache.commons.io.IOUtils;
    import sun.nio.ch.IOUtil;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    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.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * @program: JavaEE
     * @description
     * @author: wuhao
     * @create: 2019-12-16 18:54
     **/
    @WebServlet("/servlet/FileDownServlet")
    public class FileDownServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //获得服务器文件路径
            String realPath = req.getServletContext().getRealPath("/img");
    
    
            //获得文件名
            String filename = req.getParameter("filename");
    
    
            File file = new File(realPath+"/"+filename);
    
            //读取服务器文件
            FileInputStream fileInputStream = new FileInputStream(file);
    
    
    
            //设置下载文本的长度
            resp.setContentLength((int) file.length());
            // 设置文本的类型
            resp.setContentType(req.getParameter("filetype"));
            // 设置相应头
            resp.setHeader("Content-Disposition", "attachment;filename="+filename);
    
    
            //写出本地
            ServletOutputStream outputStream = resp.getOutputStream();
    
    
             IOUtils.copy(fileInputStream, outputStream);
    
    
             outputStream.close();
             fileInputStream.close();
    
    
        }
    }
    

     

    Content-Disposition属性有两种类型

    1. inline :将文件内容直接显示在页面
    2. attachment:弹出对话框让用户下载
  • 相关阅读:
    nginx--gunicorn 部署Web服务
    Hexo 搭建博客真的太简单了
    nohup 和 &
    Nginx 服务器搭建
    Django3 的服务器搭建
    Mongo 服务器的安装
    Ubuntu16.04 安装tesseract
    phantomjs 的安装
    JsonPath python
    CSS 选择器:BeautifulSoup4
  • 原文地址:https://www.cnblogs.com/ww103/p/12051505.html
Copyright © 2011-2022 走看看