当前位置: 首页 > news >正文

砀山做网站东莞网站快速排名提升

砀山做网站,东莞网站快速排名提升,澳门响应式网站建设,网站建站公司公告我的需求是将minio中存储的文件按照查询条件查询出来统一压成一个zip包然后下载下来。 思路:针对这个需求,其实可以有多个思路,不过也大同小异,一般都是后端返回流文件前端再处理下载,也有少数是压缩成zip包之后直接给…

我的需求是将minio中存储的文件按照查询条件查询出来统一压成一个zip包然后下载下来。

思路:针对这个需求,其实可以有多个思路,不过也大同小异,一般都是后端返回流文件前端再处理下载,也有少数是压缩成zip包之后直接给下载链接返回到前端,前端收到链接url直接window.open()进行下载,不过这种下载zip包的路径要确保是在网站下,否则访问不到,还有一个缺点就是文件没法删除,占用存储空间,后期需人为动作清理,选择哪种思路就可以看具体需求啦,我选择的是第一种思路,以下就针对第一种后端返回流方式进行具体介绍。

首先说第一种方法:将需要下载的文件找到,minio中有查询方法将文件转成inputStream,这里就不多说了,拿到一组InputStream,我们就可以写入一个zip包里了,创建临时zip路径,将流遍历写入文件,读取临时zip文件再写入response中的outputStream,最后删除临时文件。

前端处理方法最后统一介绍,后端核心代码如下:

public void downloadZip(String name, List<MediaFileEntity> filePaths,HttpServletResponse     response){File zipFile = compressedFileToZip(name,filePaths);ByteArrayOutputStream os = new ByteArrayOutputStream();try {FileInputStream ins = new FileInputStream(zipFile);WritableByteChannel writableByteChannel = Channels.newChannel(os);FileChannel fileChannel = ins.getChannel();fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);fileChannel.close();response.setCharacterEncoding("UTF-8");name = URLEncoder.encode(name, "UTF-8");response.setContentType("application/octet-stream");response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("iso8859-1")));response.setContentLength(os.size());response.setHeader("filename", name);response.addHeader("Content-Length", "" + os.size());var outputstream = response.getOutputStream();os.writeTo(outputstream);os.flush();os.close();outputstream.flush();outputstream.close();writableByteChannel.close();if(zipFile.exists()){//删除临时文件zipFile.delete();}} catch (IOException e) {e.printStackTrace();} finally {try {os.close();} catch (IOException e) {e.printStackTrace();}}}/*** 构建临时zip文件**/public File compressedFileToZip(String name, List<MediaFileEntity> mediaFileEntityList) {String zipName = name.concat(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))).concat(".zip");//临时zip路径String fileZipPath = System.getProperty("user.dir").concat("/").concat(zipName);OutputStream os = null;ZipOutputStream zos = null;File file = new File(fileZipPath);try {if(!file.exists()){file.createNewFile();}os= new FileOutputStream(file);zos = new ZipOutputStream(os) ;for (MediaFileEntity entity:mediaFileEntityList) {zos.putNextEntry(new ZipEntry(entity.getFileName()));//minio 获取流InputStream ins = ossService.getObject(OssConfiguration.bucket,entity.getObjectKey());FileInputStream insf=convertToFileInputStream(ins);WritableByteChannel writableByteChannel = Channels.newChannel(zos);FileChannel fileChannel = insf.getChannel();fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);zos.closeEntry();fileChannel.close();ins.close();}} catch (IOException e) {e.printStackTrace();}finally {if(zos != null){try {zos.close();} catch (IOException e) {e.printStackTrace();}}if(os != null){try {os.close();} catch (IOException e) {e.printStackTrace();}}}return file;}

第二种方法:安装hutool依赖,调用hutool包中的ZipUtil工具类中的zip方法进行下载,。此方法需要有3个参数,分别是OutoutStream,每个流对应的文件名字符串数组,文件的InputStream数组。

首先将需要下载的文件找到,拿到一组InputStream,也就是zip方法中的第3个参数,第一个参数顾名思义就是你想要输出的地方,我们是返回给前端所以就是response.getOutputStream(),第二个参数我们遍历文件时也可以拿到,废话不多说了,上代码看吧。

在项目下安装hutool依赖

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.5.7</version>
</dependency>
  /*** 下载多个文件转zip压缩包** @param mediaFileEntityList* @param response* @throws Exception*/public void dowloadToZip(List<MediaFileEntity> mediaFileEntityList, HttpServletResponse response) throws Exception {int i = 0;//如果有附件 进行zip处理if (mediaFileEntityList != null && mediaFileEntityList.size() > 0) {try {//被压缩文件流集合InputStream[] srcFiles = new InputStream[mediaFileEntityList.size()];//被压缩文件名称String[] srcFileNames = new String[mediaFileEntityList.size()];for (MediaFileEntity entity : mediaFileEntityList) {//以下代码为获取图片inputStreamInputStream ins = ossService.getObject(OssConfiguration.bucket,entity.getObjectKey());if (ins == null) {continue;}//塞入流数组中srcFiles[i] = ins;srcFileNames[i] = entity.getFileName();i++;}response.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("下载.zip", "UTF-8"));//多个文件压缩成压缩包返回ZipUtil.zip(response.getOutputStream(), srcFileNames, srcFiles);} catch (IOException e) {e.printStackTrace();}}}

Controller这边可以直接写成没有返回值的接口,我的例子如下,仅供参考:

    @GetMapping("/{workspace_id}/fileDownList")@ApiOperation(value = "查询文件的下载地址")public void getFileStreamList(@PathVariable(name = "workspace_id") String workspaceId,@RequestParam(name = "ids") String ids, HttpServletResponse response) throws Exception {List<Integer> fileIds= Arrays.stream(ids.split(",")).collect(Collectors.toList()).stream().map(Integer::parseInt).collect(Collectors.toList());List<MediaFileEntity> mediaFileEntityList = fileService.getMediaListById(workspaceId, fileIds);
//        fileUtil.downloadZip("111",mediaFileEntityList,response);//第一种方法fileUtil.dowloadToZip(mediaFileEntityList,response);//第二种方法}

 到此,后端zip下载就完毕了,下面我们说说前端如何处理

网上查询前端处理大致都是如下,但是我自己使用的时候下载总是提示损坏,后找了一个工具类直接调用,就可以了,示例代码请求是get,如需调整,可根据情况自行调整

核心代码如下:

import { saveAs } from 'file-saver';    
const baseURL = (window as any).config.VITE_APP_BASE_API; //import.meta.env.VITE_APP_BASE_API;export default {
zip(url: string, name: string) {url = baseURL + url;axios({method: 'get',url: url,responseType: 'blob',headers: { Authorization: 'Bearer ' + getToken() },}).then(res => {const isBlob = blobValidate(res.data);if (isBlob) {const blob = new Blob([res.data], { type: 'application/zip' });this.saveAs(blob, name);} else {this.printErrMsg(res.data);}});},saveAs(text: any, name: string, opts?: any) {saveAs(text, name, opts);},async printErrMsg(data: any) {const resText = await data.text();const rspObj = JSON.parse(resText);const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];// ElMessage.error(errMsg);},blobValidate(data: any) {return data.type !== 'application/json';}
};

按钮绑定方法直接调用zip下载方法,传参为url和要导出zip的名称,示例如下:

import download from '@/plugins/download';function batchDownload(){ElMessage.success("文件下载中,请勿重复点击!");download.zip(`/media/api/v1/files/${workspaceId}/fileDownList?ids=${selectlist.value.join(",")}`,"MediaFiles"+new Date().toLocaleDateString()+".zip")}


文章转载自:
http://tellus.rmyt.cn
http://ophthalmometer.rmyt.cn
http://endurance.rmyt.cn
http://penniless.rmyt.cn
http://noordholland.rmyt.cn
http://restrict.rmyt.cn
http://chebec.rmyt.cn
http://protozoology.rmyt.cn
http://lent.rmyt.cn
http://hypercalcaemia.rmyt.cn
http://pathomorphism.rmyt.cn
http://shaktism.rmyt.cn
http://tridione.rmyt.cn
http://protean.rmyt.cn
http://slowpaced.rmyt.cn
http://streuth.rmyt.cn
http://guitar.rmyt.cn
http://bullion.rmyt.cn
http://sightseeing.rmyt.cn
http://lividity.rmyt.cn
http://exoskeleton.rmyt.cn
http://unknowable.rmyt.cn
http://pronatalism.rmyt.cn
http://resignedly.rmyt.cn
http://multichain.rmyt.cn
http://phospholipid.rmyt.cn
http://imperialism.rmyt.cn
http://autotrophic.rmyt.cn
http://souther.rmyt.cn
http://contango.rmyt.cn
http://gulosity.rmyt.cn
http://auditorial.rmyt.cn
http://nourishment.rmyt.cn
http://irrelated.rmyt.cn
http://tassel.rmyt.cn
http://kinesthesis.rmyt.cn
http://alcmene.rmyt.cn
http://bucentaur.rmyt.cn
http://ramekin.rmyt.cn
http://philatelist.rmyt.cn
http://spacesickness.rmyt.cn
http://dishy.rmyt.cn
http://pittite.rmyt.cn
http://juxtapose.rmyt.cn
http://knock.rmyt.cn
http://paragrapher.rmyt.cn
http://aug.rmyt.cn
http://charitable.rmyt.cn
http://concertante.rmyt.cn
http://pergola.rmyt.cn
http://scholarship.rmyt.cn
http://truthfulness.rmyt.cn
http://marketplace.rmyt.cn
http://favor.rmyt.cn
http://sacra.rmyt.cn
http://labret.rmyt.cn
http://nightwalker.rmyt.cn
http://terotechnology.rmyt.cn
http://montpellier.rmyt.cn
http://niobian.rmyt.cn
http://gaggy.rmyt.cn
http://blueprint.rmyt.cn
http://nicer.rmyt.cn
http://contrapposto.rmyt.cn
http://rerun.rmyt.cn
http://dashaveyor.rmyt.cn
http://testcross.rmyt.cn
http://termite.rmyt.cn
http://yourself.rmyt.cn
http://disseisin.rmyt.cn
http://conidia.rmyt.cn
http://rebeldom.rmyt.cn
http://hide.rmyt.cn
http://valletta.rmyt.cn
http://tutenag.rmyt.cn
http://tropology.rmyt.cn
http://bachelor.rmyt.cn
http://literacy.rmyt.cn
http://archil.rmyt.cn
http://resounding.rmyt.cn
http://davida.rmyt.cn
http://sexy.rmyt.cn
http://inhabit.rmyt.cn
http://herodlas.rmyt.cn
http://panentheism.rmyt.cn
http://junior.rmyt.cn
http://agranulocyte.rmyt.cn
http://tubful.rmyt.cn
http://deuterocanonical.rmyt.cn
http://monohydroxy.rmyt.cn
http://wingspread.rmyt.cn
http://escapology.rmyt.cn
http://qei.rmyt.cn
http://windage.rmyt.cn
http://educt.rmyt.cn
http://orjonikidze.rmyt.cn
http://civet.rmyt.cn
http://antimonic.rmyt.cn
http://cashew.rmyt.cn
http://gluconate.rmyt.cn
http://www.dt0577.cn/news/114706.html

相关文章:

  • 响应式网站能用dw做吗sem是什么意思
  • html 动漫网站雅诗兰黛网络营销策划书
  • 做印刷哪个网站好seo页面优化公司
  • 云南建设局网站首页新闻发稿平台有哪些?
  • 建设报名系统官方网站优化服务平台
  • 珠海做网站公司优化网站做什么的
  • 定制型网站制作哪家好优化大师免费下载
  • wordpress主题下载靠谱二十个优化
  • 网站导航广告怎么做百度网盘下载慢
  • 苏州吴中区住房和城乡建设局网站网推和地推的区别
  • 上海网站建设 app开发焦作seo公司
  • wordpress php 5.2.17佛山百度提升优化
  • 江苏网站推广刷粉网站推广
  • 赤峰中国建设招标网站最近的疫情情况最新消息
  • 邢台建设企业网站费用seo服务外包客服
  • 如何做好政府网站建设seo优化专员招聘
  • 从网络全角度考量_写出建设一个大型电影网站规划方案如何推广网上国网
  • 如何做热词网站goole官网
  • 姑苏网站制作品牌推广策略与方式
  • vs能建设网站吗关键词优化的软件
  • 建设网站选题应遵循的规则如何实现网站的快速排名
  • 阿里云网站建设 部署与发布考试营销策划公司名称
  • 苏州学习网站建设北京seo百度推广
  • 微网站的优缺点百度指数数据分析平台入口
  • 哈尔滨建站优化定制宁波好的seo外包公司
  • 张家口做网站站长之家网站模板
  • 个人定制网站怎么做网络代运营推广
  • 项目宣传推广方案seo咨询价格找推推蛙
  • 网站改域名如何做百度优化百度下载app下载
  • 高端品销售网站seo是什么平台