java实现简单的文件下载
文件下载需要在WebRoot 下创建images文件夹并且放入test.txt文件创建jsp文件夹放入01.jsp
index.jsp 不变web.xml需要配置servlet 适合初学者研究学习
//index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
My JSP 'index.jsp' starting page [下载]
//jsp文件夹下的01.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
下载:test1.txt ${errorResult}
//文件下载serlvet
package com.kero99.ygc.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件下载路径
String path = getServletContext().getRealPath("/") + "images/";
String filename = req.getParameter("filename");
File file = new File(path + filename);
if(file.exists()){
//设置相应类型application/octet-stream
resp.setContentType("application/x-msdownload");
//设置头信息Content-Disposition为属性名附件形式打开下载文件指定名称为设定的filename
resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
//输入流写入输出流
InputStream inputStream = new FileInputStream(file);
ServletOutputStream ouputStream = resp.getOutputStream();
byte b[] = new byte[1024];
int n ;
//循环读取!=-1读取完毕
while((n = inputStream.read(b)) != -1){
//写入到输出流从0读取到n
ouputStream.write(b,0,n);
}
//关闭流、释放资源
ouputStream.close();
inputStream.close();
}else{
req.setAttribute("errorResult", "文件不存在下载失败!");
RequestDispatcher dispatcher = req.getRequestDispatcher("https://https://www.doczj.com/doc/6d6139236.html,/qq_17025903/article/details/jsp/01.jsp");
dispatcher.forward(req, resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}
//web.xml
xmlns:xsi="https://https://www.doczj.com/doc/6d6139236.html,/2001/XMLSchema-instance" xsi:schemalocation="https://https://www.doczj.com/doc/6d6139236.html,/xml/ns/javaee https://https://www.doczj.com/doc/6d6139236.html,/xml/ns/javaee/web-app_2_5.xsd">