Home > Backend Development > Golang > How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?

How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?

Susan Sarandon
Release: 2024-11-29 03:25:12
Original
903 people have browsed it

How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?

Zipping Content Inside a Folder Without Including the Root Folder

Problem: Zipping files within a folder results in an extracted structure that includes the root folder, whereas the desired outcome is to extract the files without the root folder.

Code Attempt:

The following code is an attempt to zip the directory structure:

func Zipit(source, target string) error {
    zipfile, err := os.Create(target)
    ...
    header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
    ...
}
Copy after login

Troubleshooting:

In the provided code, the issue lies in the line where the baseDir is being added to the header.Name. To exclude the root folder from the extracted structure, remove the baseDir from the filename.

Solution:

Replace the following line:

header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
Copy after login

with:

header.Name = strings.TrimPrefix(path, source)
Copy after login

Alternative Approaches:

Instead of manually modifying the header name, you could also use the following alternative approach to exclude the root folder during extraction:

walker := filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
    // Ignore the root directory
    if info.IsDir() && path == source {
        return filepath.SkipDir
    }
    ...
})
Copy after login

The above is the detailed content of How to Zip Files Inside a Folder Without Including the Root Folder in the Archive?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template