Commons-FileUpload组件文件下载
1)原理
a.请求(超链接),请求Servlet
b.Servlet通过文件地址将文件转为输入流,读到servlet
c.通过输出流将刚才转为输入流的文件发送给用户
2)jsp代码
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="/DownloadServlet?fileName=fortunate.png">fortunate</a>
</body>
</html>
3)servlet代码
package student.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
//获取需要下载的文件名(form,href,servlet?)
String fileName = req.getParameter("fileName");
//下载文件:需要设置响应消息头
//MIME类型,二进制文件
resp.addHeader("content-Type","application/octet-stream");
//filename包含后缀(文件名=文件名+后缀名)
resp.addHeader("content-Disposition","attachment;filename="+fileName);
resp.addHeader("content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
//根据文件的地址,将文件转为输入流(字节流)
InputStream in= getServletContext().getResourceAsStream("/res/fortunate.png");
//输出流
ServletOutputStream out = resp.getOutputStream();
//the buffer into which the data is read.缓冲区
byte[] bytes = new byte[10];
int len = -1;
in.read();
while ((len = in.read(bytes))!=-1){
out.write(bytes,0,len);
}
out.close();
in.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}