当后端接口返回的是一个流文件,如何发送请求?

145 阅读1分钟

由于ajax函数的返回类型只有xml,text,json,html等类型,并没有"流"类型,所以通过ajax去请求接口是无法下载文件。

1. 方法1 window.open()

jquery 演示
<!DOCTYPE html>
<html>
   <head>
   	<meta charset="utf-8">
   	<script src="./js/jquery-1.11.3.js"></script>
   	<title></title>
   </head>
	<body>
           <button id=”btn“>下载一个zip文件</button>
            <script type="text/javascript">
                      var $btn=$('#btn1')
                       // 已知一个下载文件的后端端口:https://xxxxxxx/xxx/xxx
                       $btn.click(function(){
                                //方法1:window.open
                                window.open('https://xxxxxxx/xxx/xxx'
                          })
             </script>
   </body>
<html>    

方法1会让浏览器自动的打开一个新的窗口,然后又会迅速关闭,用户体验非常不好

2. 方法2:通过form提交

创建一个form表单来请求接口

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="./js/jquery-1.11.3.js"></script>
		<title></title>
	</head>
 	<body>
            <button id=”btn“>下载一个zip文件</button>
             <script type="text/javascript">
                      var $btn=$('#btn')
                       // 已知一个下载文件的后端端口:
                       ar geturl="https://xxxxxxx/xxx/xxx"
                      $btn.click(function(){
                            var $form=$('<form methods="get"></form>')
                            $form.attr('action',geturl)     
                            $(document.body).append($form)
                             
                             //提交表单,实现下载
                            $form.submit() 
                      })
              </script>
    </body>
<html>    
form表单提交知识点:
示例:
		<form action="xxxx/xxxx?param4=param4" method="get"> 
			<input type="hidden" name="param1" value="param1"> 
		   	<input type="hidden" name="param2" value="param2"> 
			<input type="text" name="param3" value="param3" readonly> 
			<input type="submit" name="button1" value="submit"> 
		</form>
// form表单get提交时,action中带参数传递不了
// 但是,get请求会把form表单中的值全部作为参数传递给后端
// 例如,上面的表单form的method为get,那么提交的url:http://localhost/xxxxx/xxxxxxxt/xxxxx?pram1=param1&pram2=param2&pram3=param3&button1=submit  
// 如果用post方法提交,后台就可以收到action中的这个参数
// 例如上面的表单form的method为post,那么提交的url为:http://localhost/mywebapp/getPostServlet/getPost.do?param4=param4 --> 
// 表单的get请求中如果想传入params4这个参数,可以将参数写在input中,设置隐藏文本域
<form action="xxxx/xxxxxx" method="get">
     <input type="hidden" name="param4" value="param4">
</form>