下载代码参考

jsp页面传值:

function getBasePath(){ 
		var obj=window.location; 
		var contextPath=obj.pathname.split("/")[1]; 
		var basePath=obj.protocol+"//"+obj.host+"/"+contextPath; 
		return basePath; 
	}
var methodPath = getBasePath();
document.getElementById("exportImg").href = methodPath+ "/download/downLoadFile.do?filePath=/resources/images/linepic.png&filename=linepic.png";

controller层代码:

package com.sunyway.govhr.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/download")
public class DownLoad {

	@RequestMapping(value="/downLoadFile.do")
	public void downLoadFile(HttpServletResponse response,HttpServletRequest request,
			String filePath,String filename) throws IOException {
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		String path = request.getSession().getServletContext().getRealPath("/")+filePath;//request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径如:I:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\UMPWeb_20131230\
		File downfile = new File(path);
		try {
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-disposition", "attachment;filename="+filename);
			 
			bis = new BufferedInputStream(new FileInputStream(downfile));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[1024];
			int bytesRead;
			while(-1 != (bytesRead = bis.read(buff,0,buff.length))) {
				bos.write(buff,0,bytesRead);
			}
		} catch (Exception e) {
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
		
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值