SoFunction
Updated on 2025-03-04

Detailed tutorial on generating compressed files using Golang

This is a simple golang compressed file case, which can be expanded a lot. The library used here is archive/zip, just search for zip in gopkg.

Method 1

Using the gin framework, get the files passed from the front end and compress them into zip, and store the path into the database. The simple code example is as follows:

@Param file formData file true "Upload file"
func UploadToZip(c *){
	//Get the file transmitted from the front end. If there are multiple files: use form,_ := ()	//files := ["file"]
	// Then iterate through files to get each file	file,err := ("file")
	if err != nil {
		("The parameters are incorrect",c)
		return
	}
	//Create directory and specify file name	err = ( file ,"files/" + file + )
	if err != nil {
		("Storage file failed",c)
		return
	}
	//Generate the zip file you want in the specified directory	create, err  := ("flies/")
	defer ()
	if err != nil {
		("Creation failed",c)
		retuen
	}
	//Create a zip stream	writer := (create)
	defer ()
	//Read the stored directory and compress the files inside	readFile ,err := ("files")
	if err != nil {
		("Failed to read the file",c)
		retuen
	}
	//Travel over the directory and get a single file	for _,rf := range readFile {
		//Only compress files, directory not compressed		if !() {
			//Open the file to be compressed			open,err := ("flies" + ())
			if err != nil {
				("Failed to open the file",c)
				retuen
			}
			//Create a file and file name in a compressed package, so that after decompression, there will be a file directory with compressed files in the directory			f, _ := ("flies" + ())
			//Compress the file into zip			if _,err := (f,open);err != nil {
				("Compression failed",c)
				retuen
			}
		}
	}
	//Storing the compressed path in the database	...
	("Compression is successful",c)
}

Method 2

Compression implementation process

Create a compressed archive file

First, you need to create an archive file, just like other normal files. useosPackedfunction:

func Create(name string) (*File, error)

This method creates or deletes the given name file. If the file already exists, delete and recreate it. If it does not exist, create the file with the mode 0666. The file is successfully created and returned for reading and writing. The associated file descriptor isO_RDWR, otherwise the error is reported, the type is*PathError

Initialize the archive file

Use the archive/zip packageFunction, used to write data (file or directory) to the final compressed file.
The syntax is as follows:

func NewWriter(w ) *Writer

NewWriter Return to Writer write

Use Add File to Compress File

It has been created above, you can add files and directories to compressed files, using functions:

func (w *Writer) Create(name string) (, error)

Method adds the file to the compressed file by file name, returns Writer for writing the file content, and the file content will be compressed. The file name must be a relative path and cannot begin with a drive letter (C:) or slash, only forward slashes are allowed. If you add a directory, you need to add a tail slash after the name. The file content must be written before the next call to the Create, CreateHeader, or Close method.

Use or write file content

Return, used to write data, so any file content can be streamed into or written to the Writer, or functions can be used.

func Copy(dst Writer, src Reader) (written int64, err error)

The Copy function goes from src to dst, goes directly to EOF or encounters an error. Returns the number of bytes copied and the error (if an error occurs).

Close the compressed file using

After all files and directories are written to the compressed file, you need to close the write and generate the compressed file through the method, that is, write all data to the underlying data stream.

func (w *Writer) Close() error

Example code

The following example compresses two files (txt and csv files) to generate a single compressed file. These two files are in different subdirectories of the compressed file.

package main

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
)

func main() {
    ("creating zip archive...")
    archive, err := ("")
    if err != nil {
        panic(err)
    }
    defer ()
    zipWriter := (archive)

    ("opening first file...")
    f1, err := ("")
    if err != nil {
        panic(err)
    }
    defer ()

    ("writing first file to archive...")
    w1, err := ("csv/")
    if err != nil {
        panic(err)
    }
    if _, err := (w1, f1); err != nil {
        panic(err)
    }

    ("opening second file")
    f2, err := ("")
    if err != nil {
        panic(err)
    }
    defer ()

    ("writing second file to archive...")
    w2, err := ("txt/")
    if err != nil {
        panic(err)
    }
    if _, err := (w2, f2); err != nil {
        panic(err)
    }
    ("closing zip archive...")
    ()
}

Run the program and generate the log:

creating zip archive...
opening first file...
writing first file to archive...
opening second file
writing second file to archive...
closing zip archive...

Finally, unzip the compressed file, which is consistent with what we expect:

$ unzip -l 
Archive:  
  Length      Date    Time    Name
---------  ---------- -----   ----
       50  1980-00-00 00:00   csv/
       16  1980-00-00 00:00   txt/
---------                     -------
       66                     2 files

Summarize

The above is the detailed tutorial on using Golang to generate compressed files. For more information about Golang to generate compressed files, please pay attention to my other related articles!