通常我们通过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);