Example of displaying the pictures in the compressed package on the page

When working on a project, there is such a requirement that the preview of the pictures in the compressed package needs to be displayed.
Sort out the following three steps:

  1. download zip file
  2. Unzip the file
  3. Compose an available image URL and display it on the image tag

The process of realizing this function still took some detours, and encountered some pitfalls, so I won’t talk nonsense here, just upload the code directly, hoping to help you quickly realize this function.

The first is to download the zip and then decompress it. I use JSZIP here. The official gave us an example:

https://stuk.github.io/jszip/documentation/howto/read_zip.html

Use the JSZipUtils.getBinaryContent method to get the compressed package

Take Vue as an example, first install JSZipUtils

npm i jszip-utils

Then import JSZipUtils in the components that need to be used

import JsZip from 'jszip'

import JSZipUtils from 'jszip-utils'

The first step, download the compressed package

/*下载压缩包  返回的是个 ArrayBuffer */
const zipResp = await JSZipUtils.getBinaryContent(zipUrl)

The return is Arraybuffer
insert image description here

The second step, unzip

After getting the downloaded zip data above, you can perform the decompression operation.
code show as below

        /*解压缩 返回的是个JSZip对象*/
        var jsZip = new JsZip()
        var imgData = await jsZip.loadAsync(zipResp)

What is returned is a JSZIP object

insert image description here
As you can see, the key is the file name, and the value is the JSZipObject object.
insert image description here
What we need to focus on is the data in files.

The following is the entire code, which is relatively simple:

        /*下载压缩包  返回的是个 ArrayBuffer */
        const zipResp = await JSZipUtils.getBinaryContent(zipUrl)
        console.log('zipResp:', zipResp)
        /*解压缩 返回的是个JSZip对象*/
        var jsZip = new JsZip()
        var imgData = await jsZip.loadAsync(zipResp)
        console.log('imgData:', imgData)
        /*filesKey就是文件名*/
        for (let filesKey in imgData.files) {
    
    
          imgName = filesKey
        }
        /*找出文件转成base64*/
        var base64Img = await imgData.file(imgName).async('base64')
        /*截取出后缀名*/
        const suffixName = imgName.split('.')[0]
        /*拼接url*/
        imgUrl = `data:image/${
      
      suffixName};base64,${
      
      base64Img}` 

The above three steps can realize the function of previewing the pictures in the compressed package, hoping to help you avoid detours.


If you think this article is helpful to you, please give it a thumbs up. It can help more developers. If there are any mistakes in the article, please correct me. For reprinting, please indicate that you are reposting from Yu Zhiqiang’s blog, thank you !

Guess you like

Origin blog.csdn.net/yuzhiqiang_1993/article/details/121215351