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>