司浩宇

导航

网页下载

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/WEB04/DownloadServliet1?filename=海绵宝宝.png">海绵宝宝.png</a>
<a href="/WEB04/DownloadServliet1?filename=a.txt">a.txt</a>
<a href="/WEB04/DownloadServliet1?filename=a.wmv">a.wmv</a>
<a href="/WEB04/DownloadServliet1?filename=a.rar">a.rar</a>
</body>
</html>

  

package com.colear.demo01;

import java.io.FileInputStream;
import java.io.IOException;
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 DownloadServliet1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		获取文件名
		String filename=request.getParameter("filename");
//		解决get请求乱码
		filename=new String(filename.getBytes("ISO-8859-1"),"UTF-8");
//		告知浏览器文件的MIME类型
		response.setContentType(getServletContext().getMimeType(filename));
//		告知浏览器以附件的方式打开
		response.setHeader("Chontent-Disposition", "attachment;filename"+filename);
		 
//		明确数据源的绝对路径
		String path=getServletContext().getRealPath("/download/"+filename);
//		明确数据源
		FileInputStream fis=new FileInputStream(path);
//		明确目的地
		ServletOutputStream out=response.getOutputStream();
		byte[] bytes=new byte[1024];
		int len=0;
		while ((len=fis.read(bytes))!=-1) {
			out.write(bytes,0,len);
			
		}
//		释放资源
		fis.close();
	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

  

posted on 2021-06-17 15:25  司浩宇  阅读(108)  评论(0编辑  收藏  举报