• 不指定虚拟路径的前提下通过http访问pdf、图片等文件


      

      通常我们通过http访问图片或者pdf的时候都是将文件上传到指定文件夹下面,然后通过配置虚拟路径来访问指定的资源。

      在不配置虚拟路径的情况下,我们通过获取到response的outpurstream,然后向该outputstream输出指定的文件也可以,用IOUtils工具类更是简单方便。

    例如:

      依赖的包:

        

    package cn.qlq.web;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    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 org.apache.commons.io.IOUtils;
    
    /**
     * Servlet implementation class TestServlet
     */
    @WebServlet("/TestServlet")
    public class TestServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            FileInputStream in = null;
            ServletOutputStream outputStream = null;
            try {
                in = new FileInputStream(new File("C:\Users\Administrator\Desktop\测试文档\Java开发-太原科技大学-软件工程-乔利强.pdf"));
                outputStream = response.getOutputStream();
                IOUtils.copyLarge(in, outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(outputStream);
            }
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request, response);
        }
    
    }

    测试:

    补充:对于浏览器能解析的文件会解析,而对于浏览器不能解析的会下载,比如说docx等文件,如果想实现任何文件都下载,可以对response进行设置,如下:

                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + path);
  • 相关阅读:
    ab(http)与abs(https)压测工具
    Q_DECLARE_PRIVATE与Q_DECLARE_PUBLIC
    QMetaObject::connectSlotsByName
    使用QStringBuilder进行字符串连接
    源码必须是UTF-8,QString需要它
    Qt开发中文显示乱码
    qDebug 的使用
    qt 4.6 qmake Reference
    qmake-variable-reference
    Qt学习网站
  • 原文地址:https://www.cnblogs.com/qlqwjy/p/9510878.html
Copyright © 2020-2023  润新知