标签:public width position string 创建 attribute 总结 net 文件上传和下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件下载功能的实现。
直接贴图和代码:
1、文件列表
2、在Web.xml文件中配置DownLoadServlet
<servlet> <servlet-name>DownLoadServlet</servlet-name> <servlet-class>com.thinkplatform.controller.DownLoadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownLoadServlet</servlet-name> <url-pattern>/servlet/DownLoadServlet</url-pattern> </servlet-mapping>
3、html
<td style="width:80px;"> <c:url value="/servlet/DownLoadServlet" var="downurl"> <c:param name="path" value="${item.path}"></c:param> <c:param name="fileName" value="${item.id}"></c:param> </c:url> <a href="${downurl}">下载</a>
</td>
4、java代码
package com.thinkplatform.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownLoadServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到要下载的文件名 String fileName = request.getParameter("fileName"); //得到要下载的文件的路径 String path = request.getParameter("path"); //得到要下载的文件 File file = new File(path + "\\" + fileName); //如果文件不存在 if(!file.exists()){ request.setAttribute("message", "您要下载的资源已被删除!!"); return; } //设置响应头,控制浏览器下载该文件 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); //读取要下载的文件,保存到文件输入流 FileInputStream in = new FileInputStream(path + "\\" + fileName); //创建输出流 OutputStream out = response.getOutputStream(); //创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; //循环将输入流中的内容读取到缓冲区当中 while((len=in.read(buffer))>0){ //输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } //关闭文件输入流 in.close(); //关闭输出流 out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
标签:public width position string 创建 attribute 总结 net 文件上传和下载
原文地址:https://www.cnblogs.com/shaosks/p/9073179.html