批量选择文件,通过后台打包形成流文件提供给前端下载,一般我们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(); } }
本文介绍了一种前后端配合实现的文件批量下载方法,前端利用fetch API结合Content-Type判断,通过创建a标签实现文件下载;后端采用Java,通过设置响应头并使用ZipOutputStream打包多个文件为ZIP格式供下载。
984

被折叠的 条评论
为什么被折叠?



