不指定虛擬路徑的前提下通過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);
    }

}

 

 

測試:

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com