SpringMVC实现前后端分离下载

2017年12月14日14:06:56 发表评论 2,009 views

这个功能的需求来自最近做的项目,我的后端调用Swift服务器的文件。传回来的是byte[]的数组。目前把这个byte写到的web服务器下。然后在用现在这个方法实现web服务器下载。

现在暂时这样实现,以此文做个记录,怕未来忘记。

前端web:

选中文件,点击下载文件执行的是能弹出一个保存框去保存文件。

SpringMVC实现前后端分离下载

web前端部分代码:

name:获取选中文件的文件名

var form:伪造一个隐藏的form提交表单,提交是“name”变量。

else {
	name = $(".checked").parent().next().find("span").text();
	var form = $("<form>");
	form.attr("style", "display:none");
	form.attr("target", "");
	form.attr("method", "post");
	form.attr("action", 'downloadFile.action');
	var fileInput = $("<input>");
	fileInput.attr("type", "hidden");
	fileInput.attr("id", "name");
	fileInput.attr("name", "name");
	fileInput.attr("value", name);
	$("body").append(form);
	form.append(fileInput);
	form.submit();
	form.remove()
}

 java后端方法代码:

第一部分的try{}catch()是项目调用内容。

// 下载文件
	@RequestMapping("/downloadFile.action")
	@ResponseBody
	public void downloadFile(String name,HttpServletRequest request,HttpServletResponse response
			/*@RequestParam(value = "name", required = true) String name*/) throws FileNotFoundException {
		String rpath, downPath;
		// 用户
		User user = getSessionUser(request);
		String username = user.getUsername();
		rpath = username + "/" + getPath + name;
		byte buf[] = swiftStorageService.downloadFile(rpath);
		// downPath = "upload/" + name;
		downPath = request.getSession().getServletContext().getRealPath("/")
				+ "upload/" + name;
		System.out.println("downPath:" + downPath);
		File file = new File(downPath);
		FileOutputStream fileout = null;
		try {
			fileout = new FileOutputStream(file);
			fileout.write(buf);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileout.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		File rfile = new File(downPath);
		response.setContentType("application/force-download");// 设置强制下载不打开
	    response.addHeader("Content-Disposition",
	                       "attachment;fileName=" + name);// 设置文件名
		byte[] buffer = new byte[1024];
		BufferedInputStream bis = null;
		System.out.println("downPath:" + downPath);
		try{
			bis = new BufferedInputStream(new FileInputStream(rfile));
			OutputStream out = response.getOutputStream();
			int len = 0;
			while((len = bis.read(buffer))!=-1){
				out.write(buffer, 0, len);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

好了未优化的记录就到此了。

 

 

 


欢迎来到菜鸟头头的个人博客
本文章百度已收录,若发现本站有任何侵犯您利益的内容,请及时邮件或留言联系,我会第一时间删除所有相关内容。

  • A+
所属分类:JAVA

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: