使用javaweb實(shí)現(xiàn)圖片下載的代碼
package cn.itcast.web.download;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
?* Servlet implementation class DownloadServlet
?*/
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
?? ?private static final long serialVersionUID = 1L;
????? ?
??? /**
???? * @see HttpServlet#HttpServlet()
???? */
??? public DownloadServlet() {
??????? super();
??????? // TODO Auto-generated constructor stub
??? }
?? ?/**
?? ? * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
?? ? */
?? ?protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
?? ??? ?//1.獲取請(qǐng)求參數(shù),文件名稱
?? ??? ?String filename = request.getParameter("filename");
?? ??? ?//2.使用字節(jié)輸入流加載文件進(jìn)內(nèi)存
?? ??? ?//2.1找到文件服務(wù)器路徑
?? ??? ?ServletContext servletContext = this.getServletContext();
?? ??? ?String realPath = servletContext.getRealPath("/img/"+filename);
?? ??? ?//2.2用字節(jié)流關(guān)聯(lián)
?? ??? ?FileInputStream fis=new FileInputStream(realPath);//將圖片讀進(jìn)內(nèi)存
?? ??? ?//3.設(shè)置response的響應(yīng)頭
?? ??? ?//3.1設(shè)置響應(yīng)頭類型:content-type
?? ??? ?String mimeType = servletContext.getMimeType(filename);//獲取文件的mime類型
?? ??? ?response.setHeader("content-type", mimeType);
?? ??? ?//3.2設(shè)置響應(yīng)頭的打開方式
?? ??? ?response.setHeader("content-disposition", "attachment;filename="+filename);
?? ??? ?//4.將輸入流的數(shù)據(jù)寫出到輸出流中
?? ??? ?ServletOutputStream sos = response.getOutputStream();
??????? byte[] buff = new byte[1024 * 8];
??????? int len = 0;
??????? while((len = fis.read(buff)) != -1){
??????????? sos.write(buff,0,len);
??????? }
??????? fis.close();?? ?}
?? ?/**
?? ? * @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);
?? ?}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/Project3/img/1.jpg">圖片</a>
<hr>
<a href="/Project3/DownloadServlet?filename=1.jpg">圖片</a>
</body>
</html>