首页 > 其他分享 >多文件,从url地址中下载文件并进行压缩

多文件,从url地址中下载文件并进行压缩

时间:2022-09-05 09:02:01浏览次数:70  
标签:文件 String tar url 压缩 file new null response

直接上代码

Controller层

	//我这里直接拿实体接收,entity.getFile()是List<对象>,对象里面存储文件相关的内容
    @PostMapping("/zipDownload")
    @ApiOperation(value = "文件导出", notes = "作者:hhs")
    public Object downloadallfiles(HttpServletRequest req, HttpServletResponse response, @RequestBody BenbuBean entity) {
        return benbuService.downloadallfiles(req, response, entity.getFile());
    }

业务层

	@Override
	public ReturnObject<Object> downloadallfiles(HttpServletRequest request, HttpServletResponse response, List<UploadFile> files) {
		List<String> urls = new ArrayList<String>();
		ReturnObject<Object> returnObject = new ReturnObject<Object>();
		if (files != null && files.size() > 0) {
			for (UploadFile file : files) {
				String url = sso.getPresignedObjectUrlByBucketNameAndPath(file.getBucketname(), file.getFilepath());
				urls.add(url);
			}
		}
		// 响应头的设置
		response.reset();
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.addHeader("Access-Control-Allow-Origin","*"); //时间太长会中断连接

		// 设置压缩包的名字
		// 解决不同浏览器压缩包名字含有中文时乱码的问题
		String downloadName = "****.zip";
		String agent = request.getHeader("USER-AGENT");
		try {
			if (agent.contains("MSIE") || agent.contains("Trident")) {
				downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
			} else {
				downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1"); //必写
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

		// 设置压缩流:直接写入response,实现边压缩边下载
		ZipOutputStream zipos = null;
		try {
			zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
			zipos.setMethod(ZipOutputStream.DEFLATED); // 设置压缩方法
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 循环将文件写入压缩流
		DataOutputStream os = null;
		int t =0;
		for (String notes : urls) {
			String fileName =  UrlFilesToZip.getFileTypeByUrl(notes);//通过连接获取文件类型 文件名没有文件类型后缀时偶这个方法
			// 这里,加上t是防止要下载的文件有重名的导致下载失败
			//String fileName=notes.substring(25, 29).toUpperCase()+t;
			File file = UrlFilesToZip.getFileByUrl(notes, fileName);
			try {
				// 添加ZipEntry,并ZipEntry中写入文件流
				zipos.putNextEntry(new ZipEntry(fileName));
				os = new DataOutputStream(zipos);
				InputStream is = new FileInputStream(file);
				byte[] b = new byte[1024];
				int length = 0;
				while ((length = is.read(b)) != -1) {
					os.write(b, 0, length);
				}
				is.close();
				zipos.closeEntry();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 关闭流
		try {
			os.flush();
			os.close();
			zipos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

实体层

public class UrlFilesToZip {

    private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);


    //url转file
    public static File getFileByUrl(String fileUrl, String suffix) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        File file = null;
        try {
            URL imageUrl = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = File.createTempFile("file", suffix);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (stream != null)
                    stream.close();
                outStream.close();
            } catch (Exception e) {
            }
        }
        return file;
    }

    //根据获取文件后缀
    public static String getFileTypeByUrl(String url) {

        String suffixes = "3fr|arw|bmp|cr2|crw|dcr|dng|eps|erf|gif|icns|ico|jpeg|jpg|mos|mrw|nef|odd|orf|pdf|pef|png|ppm|ps|psd|raf|raw|svg|svgz|tif|tiff|webp|x3f|xcf|xps|		7z|ace|alz|arc|arj|bz|bz2|cab|cpio|deb|dmg|eml|gz|img|iso|jar|lha|lz|lzma|lzo|rar|rpm|rz|tar|tar.7z|tar.bz|tar.bz2|tar.gz|tar.lzo|tar.xz|tar.Z|tbz|tbz2|tgz|tZ|tzo|xz|z|zip|aac|ac3|aif|aifc|aiff|amr|caf|flac|m4a|m4b|mp3|oga|ogg|sf2|sfark|voc|wav|weba|wma|		3g2|3gp|3gpp|avi|cavs|dv|dvr|flv|gif|m2ts|m4v|mkv|mod|mov|mp4|mpeg|mpg|mts|mxf|ogg|rm|rmvb|swf|ts|vob|webm|wmv|wtv|		abw|djvu|doc|docm|docx|html|lwp|md|odt|pages|pages.zip|pdf|rst|rtf|sdw|tex|txt|wpd|wps|zabw|eps|html|key|key.zip|odp|pdf|pps|ppsx|ppt|pptm|pptx|ps|sda|swf|		csv|html|numbers|numbers.zip|ods|pdf|sdc|xls|xlsm|xlsx|azw|azw3|azw4|cbc|cbr|cbz|chm|docx|epub|fb2|htm|html|htmlz|lit|lrf|mobi|odt|oeb|pdb|pdf|pml|prc|rb|rtf|snb|tcr|txt|txtz|eot|otf|ttf|woff|dwg|dxf|ai|cdr|cgm|emf|eps|pdf|ps|sk|sk1|svg|svgz|vsd|wmf|website";
        Pattern pat = Pattern.compile("[\\w]+[\\.](" + suffixes + ")");// 正则判断
        Matcher mc = pat.matcher(url);// 条件匹配
        String substring = "";
        while (mc.find()) {
            substring = mc.group();// 截取文件名后缀名
        }
        return substring;
    }

`

标签:文件,String,tar,url,压缩,file,new,null,response
From: https://www.cnblogs.com/hhs-5120/p/16656848.html

相关文章

  • 什么?MySQL 8.0 会同时修改两个ib_logfilesN 文件?
    GreatSQL社区原创内容未经授权不得随意使用,转载请联系小编并注明来源。GreatSQL是MySQL的国产分支版本,使用上与MySQL一致。作者介绍:孙黎,GreatDB认证DBA问题现象描述......
  • 文件导出ZIP压缩
    文件导出ZIP压缩 @OverridepublicStringdownloadallfiles(HttpServletRequestrequest,StringlsbpId,StringbsTitle){ JwtUserObjectjwtUserObject=JwtUtil.g......
  • 标准化手册文件
    很多企业需要相关的标准化手册文件,但每家企业的文化、团队、模式、架构、产品、服务、定位、能力、资金实力、重视程度…都不一样。所以即使拿到了也没法使用,要不然的话......
  • linux 增加swap分区容量 --文件方式
    背景:用笔记本做openstack测试时,由于需要同时开启多台虚拟机且每台内存要求8G以上,笔记本硬件已无法满足,故通过增加swap的方式处理操作一、查看扩容前swap分区容量fre......
  • Pycharm生成allure报告报错--allure不是内部或外部命令,也不是可运行的程序 或批处理文
    问题:allure报错:‘allure’不是内部或外部命令,也不是可运行的程序或批处理文件 截图:  解决方法:1.安装JDK(版本1.8+),配置环境变量此处不展示过程,成功的后进入cmdjava-version......
  • 【django学习-08】视图之HttpResponse文件下载
    一:前言:响应内容除了返回网页信息外,还可以实现文件下载功能,是网站常用的功能之一。Django提供三种方式实现文件下载功能,分别是HttpResponse,StreamingHttpResponse和FileRe......
  • java复制文件的4种方式及拷贝文件到另一个目录下的实例代码
    java复制文件的4种方式及拷贝文件到另一个目录下的实例代码这篇文章主要介绍了java复制文件的4种方式,通过实例带给大家介绍了java拷贝文件到另一个目录下的方法,需要的......
  • 第三方库openPyxl读取excel文件
    importopenpyxlfromopenpyxl.worksheet.worksheetimportWorksheetdefopenpyxl_read():#1、打开文件workbook=openpyxl.load_workbook("cases.xlsx")......
  • python 打包代码成可执行文件
    python项目打包成可执行文件为了方便程序的运行,Python提供了第三方库pyinstaller可以很方便的将项目打包成可执行的exe程序,安装方法:pipinstallpyinstaller1、使用方法:......
  • ansible加密解密文件(vault)
                                 ......