SpringMVC使用ajax 实现文件下载

SpringMVC使用ajax 实现文件下载

一、说明结论
1、 ajax 是无法实现文件下载的,原因:ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,虽然可以读取到返回的response,但只是读取而已,是无法执行的。 ( 引用自这里

二、文件下载后台代码
    @RequestMapping(value="/downloadFile")
	public String downloads(HttpServletResponse response) throws Exception{
		String	path = "C:/";
		String  fileName = "default.png";
		File file = new File(path,fileName);
		
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", 
				"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
		InputStream input=new FileInputStream(file);
		OutputStream out = response.getOutputStream();
		byte[] buff =new byte[1024];
		int index=0;
		while((index= input.read(buff))!= -1){
			out.write(buff, 0, index);
			out.flush();
		}
		out.close();
		input.close();
		return null;
	}
三、 前台代码
1、 html 代码
<button id="download">点击下载文件</button>
2、使用 ajax 尝试下载文件
<script type="text/javascript">
	    $("#download").click(function(){
		var url="/downloads/ajax/file";//下载文件url
		$.ajax({
		    url:url,
		    type:'post',
		    data:{},
		    success:function(data){
			console.info(data,typeof data);
		    }
		});
	    });
        </script>

    3、结果: 没有出现文件下载,出现如下图所示内容:
    

四、解决办法
1、 使用 window.location.href ,缺点: 仅支持 get 请求
<script type="text/javascript">
	        $("#download").click(function(){
		    var url="/downloads/ajax/file";//下载文件url
		    window.location.href=url;	
		});
	</script>

    2、使用隐藏表单
a. html 代码
<form action="" id="fileForm" method="post" style="display: none;"></form>

b. js 代码
<script type="text/javascript">
	    $("#download").click(function(){
		var url="/downloads/ajax/file";//下载文件url
		$("#fileForm").attr('action',url);
		$("#fileForm").submit();
	    });
        </script>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章