批量選擇文件,通過后台打包形成流文件提供給前端下載,一般我們request.js都會做一些驗證與報錯提示,但是不支持文件下載。
而文件下載中,前端的解決方法可以通過響應頭的Content-Type
來判斷。
直接上代碼:
export async function apiBatchSave (params) { return fetch(`${API_DOC_JAVA}/batchSave`,{ method: 'POST', headers: { 'Accept': 'application/json, */*', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'cache': 'default', 'x-ajax': 'true' }, 'credentials': 'include', //表示請求是否攜帶cookie body: formartBody(params) }).then(function (response) { if (response.ok) { response.blob().then((blob) => { const a = window.document.createElement('a'); const downUrl = window.URL.createObjectURL(blob);// 獲取 blob 本地文件連接 (blob 為純二進制對象,不能夠直接保存到磁盤上) const filename = response.headers.get('Content-Disposition').split('filename=')[1].split('.'); a.href = downUrl; a.download = `${decodeURI(filename[0])}.${filename[1]}`; a.click(); window.URL.revokeObjectURL(downUrl); }); return {state: 1} } else { throw new Error('') } }) }
java后端配置
public void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName){ try{ response.setContentType("application/x-msdownload"); response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(zipName, "utf-8")); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); BufferedOutputStream bos = new BufferedOutputStream(zos); for(Map.Entry<String, byte[]> entry : files.entrySet()){ String fileName = entry.getKey(); //每個zip文件名 byte[] file = entry.getValue(); //這個zip文件的字節 BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file)); zos.putNextEntry(new ZipEntry(fileName)); int len = 0; byte[] buf = new byte[10 * 1024]; while( (len=bis.read(buf, 0, buf.length)) != -1){ bos.write(buf, 0, len); } bis.close(); bos.flush(); } bos.close(); }catch(Exception e){ e.printStackTrace(); } }