之前一直在网上搜索后台怎么发送文件,前台怎么接收,一直没找到特别合适的,折腾了很长时间,后来发现常做web的人说这是一个非常简单的功能,可能因为其他人都觉得太简单了。。
首先是前台将下载放在一个button或者a标签之类的,实现点击事件,例子中是根据一个id,去查找下载文件
window.location.href的作用就是去浏览器上访问这个下载文件的url
<button type="button" class="btn btn-warning" οnclick="returnID()">下载</button>
function returnID(){
var row = $.map($('#table').bootstrapTable('getSelections'),function(row){return row;});
var url = '<c:url value="/file/download2?id='+row[0].id+'"/>';
window.location.href=url;
}
后台程序如下,程序实现后,在后台点击之后浏览器就会弹出要下载的提示框:
@RequestMapping(value = "/file/download2",method = RequestMethod.GET)
@ResponseBody
public void download2(HttpServletRequest request,HttpServletResponse response) {
String id = request.getParameter("id");
String filePath = this.getClass().getResource("/").getPath();
boolean ret = createFile(2,filePath,entity);
//根据id可以制作文件,制作文件过程,这里不再展示
String path = StringUtils.substringAfter(filePath, "/");
String downloadFile = path + File.separator + "要发送的文件.txt";
if(file.exists()){
File file =new File(downloadFile);
try {
System.err.println("start sleep");
Thread.sleep(2000);System.err.println("end sleep");
} catch (InterruptedException e1) {
// TODO Auto-generated catch blocke1.printStackTrace();
}//向页面发送文件
String filePath = filePath+"要发送的文件.txt";
//获取文件长度
long fileLen = new File(filePath).length();
//设置文件输出类型
response.setContentType("application/octet-stream");
try {
response.setHeader("Content-disposition", "attachment; filename="
+ new String("要发送的文件.txt".getBytes("utf-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} //设置输出长度
response.setHeader("Content-Length", String.valueOf(fileLen));
//获取输入流
//输出流
FileInputStream bis=null;
OutputStream stream = null;
try {System.err.println("开始发送文件");
bis = new FileInputStream(filePath);stream = response.getOutputStream();
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
stream.write(buff, 0, bytesRead);
}
stream.flush();
stream.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}}}