• Servlet实现文件下载


    package com.aib.soft;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URLEncoder;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class download extends HttpServlet {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	public void doGet(HttpServletRequest request, HttpServletResponse res)
    			throws ServletException, IOException {
    
    		//获取资源的绝对路径
    		String path = this.getServletContext().getRealPath("/image/gr.jpg");
    		//获取资源名
    		String filename = path.substring(path.lastIndexOf("\") + 1);
    		// 以下载方式打开的响应头content-disposition,并用URLEncoder.encode方法转码
    		res.setHeader("content-disposition", 
    				"attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
    
    		//获取字节流(非文本资源必须用字节流)
    		OutputStream out = res.getOutputStream();
    		//文件输入流
    		InputStream in=new FileInputStream(path);
    		
    		//向代表客户端的response输出资源
    		byte[] buf=new byte[1024];
    		int len=0;
    		while((len=in.read(buf))>0){
    			out.write(buf, 0, len);
    		}
    		//out.flush();  response由Servlet管理,可不关闭流
    		//out.close();
    		in.close(); // 由程序员自己管理 
    		System.out.println("-------s");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    	}
    
    }
    

      

  • 相关阅读:
    PHP date函数时间相差8个小时解决办法
    PHP中include()与require()的区别说明
    post与get区别
    MFC 对话框控件自动布局
    Apache php Mysql部署(一)下载安装
    apache 重定向
    clistctrl失去焦点高亮显示选中行
    格式化字符串
    unicode编码与utf-8 区别
    string的实现
  • 原文地址:https://www.cnblogs.com/lolita/p/3253118.html
Copyright © 2020-2023  润新知