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();
}
}
}
}