文件下载
来源:互联网 发布:淘宝引导下单转化率 编辑:程序博客网 时间:2024/06/06 01:14
首先Servlet
import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;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 DownServlet */@WebServlet("/DownServlet")public class DownServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DownServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String path=request.getParameter("path"); path=new String(path.getBytes("GBK"),"GBK"); File file=new File(path); InputStream in=new FileInputStream(file); OutputStream os=response.getOutputStream(); response.addHeader("Content-Disposition", "attachment;filename="+new String(file.getName())); response.addHeader("Content-Length",file.length()+""); response.setCharacterEncoding("GBK"); response.setContentType("application/octet-stream"); int data=0; while((data=in.read())!=-1){ os.write(data); } os.close(); in.close(); }}
index.jsp
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%><!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=GBK"><title>Insert title here</title></head><body> <a href="DownServlet?path=<%=getServletContext().getRealPath("123.mp3") %>">下载</a></body></html>
然后我们看看布局,就是你的目录下必须有一个mp3文件
运行结果
然后结束啦
0 0
- 下载图片,下载文件
- 文件下载
- 文件下载
- 文件下载
- 文件下载
- 文件下载
- 文件下载
- 下载文件
- 文件下载
- 下载文件
- 文件下载
- 文件下载
- 下载文件
- 文件下载
- 下载文件
- 下载文件
- 文件下载
- 下载文件
- hdu 1198 Farm Irrigation
- Manacher算法学习
- 【Flask】Flask实现异步非阻塞请求功能
- 【Linux4.1.12源码分析】协议栈报文接收之IP层处理分析(ip_local_deliver)
- NYOJ 927 The partial sum problem
- 文件下载
- HDU 2024 C语言合法标识符(笑)
- 编写ios和android共用的c/c++库时 使用iconv的问题
- ISDN线路编码介绍
- 制作九九表(乘法口诀表)
- 树莓派3 入门
- ASP.NET 常用的三十三种代码
- Android官方数据绑定框架DataBinding
- 技术的正宗与野路子