Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize multiple File Compression and download by java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "java how to achieve multi-file compression download", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "java how to achieve multi-file compression download" this article.

Demand:

After the revision of the member operation platform, many full download links have been added to the page. Last week, the launch was relatively hasty. All downloads are a link to download ZIP compressed files directly. Each ZIP compressed file is compressed into a ZIP compressed file by the company's operators, and then uploaded to the document information system through the company's trading operation platform. On the other hand, the member operation platform can directly obtain the address of ZIP compressed files for download.

Here is an example of a page:

Requirements Analysis:

Through the analysis of the above requirements and pages, it can be concluded that it is indeed an urgent solution for the company operator to upload the file data system after ZIP compression of all the files that need to be downloaded on the page, but taking into account the subsequent changes in requirements, the files that the page needs to download will also be changed. Every time the change needs, the company operators need to re-compress the files, and the program also needs to be modified accordingly. This is not friendly to the maintainability of the program, and from the point of view of the customer who uses the system, it needs to be re-uploaded every time, so the temporary solution is no longer in line with the good expansibility and convenient operation of the software. therefore, there is a need to download all the files on the page to use the program compression processing and download.

The solution is as follows:

Step 1: the front end passes the Ids string

Since the member operating system shows that the file to be downloaded is the Id of each file record in the data system, the front-end page only needs to pass all the file Ids strings that need to be downloaded (for example: '1213') to the background.

Step 2: background processing

First, get the ids string passed by the front end, convert it to the ids array of Integer [], and then call the file data micro service to query the corresponding file records (including file type, file address path and other information) according to the id list, obtain all the file paths that need to be downloaded, and then compress the files into ZIP format for download.

Attach the complete code:

Compress download Controller

Package com.huajin.jgoms.controller.user; import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.List;import java.util.Objects;import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.CollectionUtils;import org.apache.commons.lang3.ObjectUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping Import com.huajin.baymax.logger.XMsgError;import com.huajin.baymax.logger.Xlogger;import com.huajin.common.util.UUIDUtil;import com.huajin.exchange.domain.sys.FeFileCenter;import com.huajin.exchange.enums.sys.SysParamKey;import com.huajin.exchange.po.sys.SysParamPo;import com.huajin.jgoms.controller.HjBaseController;import com.huajin.jgoms.service.FeFileCenterService;import com.huajin.jgoms.service.SysParamService;import com.huajin.jgoms.util.CompressDownloadUtil / * compressed download file * * @ author hongwei.lian * @ date 6:29:05 on September 6, 2018 * / @ Controller@RequestMapping ("/ compressdownload") public class CompressDownloadController extends HjBaseController {@ Autowired private FeFileCenterService feFileCenterService; @ Autowired private SysParamService sysParamService / * Multi-file compression download * * @ author hongwei.lian * @ date 6:28:56 on September 6, 2018 * / @ RequestMapping ("/ downloadallfiles") public void downloadallfiles () {/ /-- 1, according to the ids query downloaded file address list String ids = request (). GetParameter ("ids"); if (StringUtils.isEmpty (ids)) {return } / /-- change the string array to an integer array Integer [] idsInteger = CompressDownloadUtil.toIntegerArray (ids); List fileCenters = feFileCenterService.getFeFileByIds (super.getExchangeId (), idsInteger); if (CollectionUtils.isNotEmpty (fileCenters) & & ObjectUtils.notEqual (idsInteger.length, fileCenters.size () {/ /-- the number of Id arrays to download files and the number of returned file addresses are inconsistent return } / /-- 2. Convert to file list List files = this.toFileList (fileCenters); / /-- check whether for (File file: files) {if (! file.exists ()) {/ /-- exists the address return in the file list that needs to be downloaded;}} / /-- 3, the setting of the response header String downloadName = UUIDUtil.getUUID () + ".zip" HttpServletResponse response = CompressDownloadUtil.setDownloadResponse (super.response (), downloadName); / /-- 4. The first scheme: / /-- specify the ZIP package path / / String zipFilePath = this.setZipFilePath (downloadName); / / try {/-compress multiple files to the specified path / / CompressDownloadUtil.compressZip (files, new FileOutputStream (zipFilePath)); /-- download the package / / CompressDownloadUtil.downloadFile (response.getOutputStream (), zipFilePath) /-- Delete the temporarily generated ZIP file / / CompressDownloadUtil.deleteFile (zipFilePath); / /} catch (IOException e) {/ / Xlogger.error (XMsgError.buildSimple (CompressDownloadUtil.class.getName (), "downloadallfiles", e)); / /} /-- 5. The second scheme: try {/ /-- compress multiple files into the response output stream CompressDownloadUtil.compressZip (files, response.getOutputStream ()) } catch (IOException e) {Xlogger.error (XMsgError.buildSimple (CompressDownloadUtil.class.getName (), "downloadallfiles", e));}} / * set the path to the temporarily generated ZIP file * * @ param fileName * @ return * @ author hongwei.lian * @ date 3:54:13 * / private String setZipFilePath (String fileName) {String zipPath = sysParamService.getCompressDownloadFilePath (); File zipPathFile = new File (zipPath) If (! zipPathFile.exists ()) {zipPathFile.mkdirs ();} return zipPath + File.separator + fileName } / * convert fileCenters list to File list * * @ param fileCenters * @ return * @ author hongwei.lian * @ date 6:54:16 * / private List toFileList (List fileCenters) {return fileCenters.stream () .map (feFileCenter-> {/ /-get the path of each file String filePath = this.getSysFilePath (feFileCenter.getFileTypeId ()); return new File (filePath + feFileCenter.fileLink ()) }) .storage (Collectors.toList ());} / * get the storage path corresponding to the file type * * @ param fileTypeId * @ return * @ author hongwei.lian * @ date 2:01:53 on September 5, 2018 * / private String getSysFilePath (Integer fileTypeId) {SysParamPo sysmParam = sysParamService.getByParamKey (SysParamKey.FC_UPLOAD_ADDRESS.value); String filePath = Objects.nonNull (sysmParam)? SysmParam.getParamValue (): "; return filePath + fileTypeId + File.separator;}}

Compressed download utility class

Package com.huajin.jgoms.util; import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Arrays;import java.util.List;import java.util.Objects;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; import com.huajin.baymax.logger.XMsgError;import com.huajin.baymax.logger.Xlogger / * * compressed download tool class * * @ author hongwei.lian * @ date 6:34:56 * / public class CompressDownloadUtil {private CompressDownloadUtil () {} / * set download response header * * @ param response * @ return * @ author hongwei.lian * @ date 3:01:59 on September 7, 2018 * / public static HttpServletResponse setDownloadResponse (HttpServletResponse response, String downloadName) {response.reset () Response.setCharacterEncoding ("utf-8"); response.setContentType ("application/octet-stream"); response.setHeader ("Content-Disposition", "attachment;fileName*=UTF-8''" + downloadName); return response } / * string converted to integer array * * @ param param * @ return * @ author hongwei.lian * @ date 6:38:39 * / public static Integer [] toIntegerArray (String param) {return Arrays.stream (",") .map (Integer::valueOf) .toArray (Integer []:: new) } / * compress multiple files into the specified output stream * * @ param files the list of files to be compressed * @ param outputStream to the specified output stream * @ author hongwei.lian * @ date 3:11:59 on September 7, 2018 * / public static void compressZip (List files, OutputStream outputStream) {ZipOutputStream zipOutStream = null; try {/-- wrapped in ZIP format output stream zipOutStream = new ZipOutputStream (new BufferedOutputStream (outputStream)) / /-- set compression method zipOutStream.setMethod (ZipOutputStream.DEFLATED); / /-write multiple files to the package for (int I = 0; I < files.size (); iCompression +) {File file = files.get (I); FileInputStream filenputStream = new FileInputStream (file); byte [] data = new byte [(int) file.length ()]; filenputStream.read (data) / /-- add ZipEntry, and write the file stream in ZipEntry. Here, I is added to prevent the file to be downloaded from having duplicate names that lead to download failure zipOutStream.putNextEntry (new ZipEntry (I + file.getName ()); zipOutStream.write (data); filenputStream.close (); zipOutStream.closeEntry ();}} catch (IOException e) {Xlogger.error (XMsgError.buildSimple (CompressDownloadUtil.class.getName (), "downloadallfiles", e) } finally {try {if (Objects.nonNull (zipOutStream)) {zipOutStream.flush (); zipOutStream.close ();} if (Objects.nonNull (outputStream)) {outputStream.close ();}} catch (IOException e) {Xlogger.error (XMsgError.buildSimple (CompressDownloadUtil.class.getName (), "downloadallfiles", e)) } / * download file * * @ param outputStream download output stream * @ param zipFilePath path to download the file * @ author hongwei.lian * @ date 3:27:08 on September 7, 2018 * / public static void downloadFile (OutputStream outputStream, String zipFilePath) {File zipFile = new File (zipFilePath); if (! zipFile.exists ()) {/ /-- there is no return for the pressed package file to be downloaded } FileInputStream inputStream = null; try {inputStream = new FileInputStream (zipFile); byte [] data = new byte [(int) zipFile.length ()]; inputStream.read (data); outputStream.write (data); outputStream.flush ();} catch (IOException e) {Xlogger.error (XMsgError.buildSimple (CompressDownloadUtil.class.getName (), "downloadZip", e));} finally {try {if (Objects.nonNull (inputStream)) {inputStream.close ();} if (Objects.nonNull (outputStream)) {outputStream.close () } catch (IOException e) {Xlogger.error (XMsgError.buildSimple (CompressDownloadUtil.class.getName (), "downloadZip", e));} / * Delete the file in the specified path * * @ param filepath * @ author hongwei.lian * @ date 3:44:53 on September 7, 2018 * / public static void deleteFile (String filepath) {File file = new File (filepath); deleteFile (file) } / * delete the specified file * * @ param file * @ author hongwei.lian * @ date 3:45:58 * / public static void deleteFile (File file) {/ /-- if the path is a file and is not empty, delete if (file.isFile () & & file.exists ()) {file.delete ();}

The above is all the contents of the article "how to achieve multi-file compression and download in java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report