后端代碼:
可以把請(qǐng)求設(shè)置為post恕出,我這里是Get
@RequestMapping(value = "/download", method = RequestMethod.POST)
? ? public void download(HttpServletRequest request, HttpServletResponse res) throws Exception {
? ? ? ? File excelFile = new File("/Users/i501695/GitHUbProject/EN_ProductIntergration/databaseclient/src/main/resources/Files/ProductTemplateCopy.xlsx");
? ? ? ? res.setCharacterEncoding("UTF-8");
? ? ? ? String realFileName = excelFile.getName();
? ? ? ? res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
? ? ? ? res.setContentType("application/octet-stream;charset=UTF-8");
? ? ? ? //加上設(shè)置大小下載下來(lái)的.xlsx文件打開(kāi)時(shí)才不會(huì)報(bào)“Excel 已完成文件級(jí)驗(yàn)證和修復(fù)蛾找。此工作簿的某些部分可能已被修復(fù)或丟棄”
? ? ? ? res.addHeader("Content-Length", String.valueOf(excelFile.length()));
? ? ? ? try {
? ? ? ? ? ? res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(), "UTF-8"));
? ? ? ? } catch (UnsupportedEncodingException e1) {
? ? ? ? ? ? e1.printStackTrace();
? ? ? ? }
? ? ? ? byte[] buff = new byte[1024];
? ? ? ? BufferedInputStream bis = null;
? ? ? ? OutputStream os = null;
? ? ? ? try {
? ? ? ? ? ? os = res.getOutputStream();
? ? ? ? ? ? bis = new BufferedInputStream(new FileInputStream(excelFile));
? ? ? ? ? ? int i = bis.read(buff);
? ? ? ? ? ? while (i != -1) {
? ? ? ? ? ? ? ? os.write(buff, 0, buff.length);
? ? ? ? ? ? ? ? os.flush();
? ? ? ? ? ? ? ? i = bis.read(buff);
? ? ? ? ? ? }
? ? ? ? }catch (Exception e){
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }finally {
? ? ? ? ? ? if (bis != null) {
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? bis.close();
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
前端偽代碼結(jié)合Axios(核心代碼一樣烤黍,只是結(jié)合了Axios)
Axios({ // 用axios發(fā)送post請(qǐng)求
? ? ? ? ? ? ? ? method: 'post',
? ? ? ? ? ? ? ? url: 'http://127.0.0.1:8762/dataService/download', // 請(qǐng)求地址
? ? ? ? ? ? ? ? data: formData, // 參數(shù)
? ? ? ? ? ? ? ? responseType: 'blob' // 表明返回服務(wù)器返回的數(shù)據(jù)類(lèi)型
? ? ? ? ? ? })
? ? ? ? ? ? ? ? .then((res) => { // 處理返回的文件流
? ? ? ? ? ? ? ? ? ? let blob = new Blob([res.data], {type: res.data.type})
? ? ? ? ? ? ? ? ? ? const fileName = 'ProductTemplateCopy.xlsx';
? ? ? ? ? ? ? ? ? ? let downloadElement = document.createElement('a')
? ? ? ? ? ? ? ? ? ? let href = window.URL.createObjectURL(blob); //創(chuàng)建下載的鏈接
? ? ? ? ? ? ? ? ? ? downloadElement.href = href;
? ? ? ? ? ? ? ? ? ? downloadElement.download = fileName; //下載后文件名
? ? ? ? ? ? ? ? ? ? document.body.appendChild(downloadElement);
? ? ? ? ? ? ? ? ? ? downloadElement.click(); //點(diǎn)擊下載
? ? ? ? ? ? ? ? ? ? document.body.removeChild(downloadElement); //下載完成移除元素
? ? ? ? ? ? ? ? ? ? window.URL.revokeObjectURL(href); //釋放blob
? ? ? ? ? ? ? ? ? ? message.success('upload successfully.');
? ? ? ? ? ? })
? ? ? ? ? ? .catch(function (error) {
? ? ? ? ? ? ? ? console.log(error);
? ? ? ? ? ? });