Zipping Content within a Folder without the Root Folder
The requirement is to create a ZIP file containing the files within a directory, excluding the directory itself as the root folder upon extraction.
The provided snippet attempts to achieve this by setting the header name using the following line:
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
However, this code adds the base directory (e.g., "dir1") to the header name, resulting in an archive where the files are nested within the directory structure.
To address this issue, the line should be replaced with the following:
header.Name = strings.TrimPrefix(path, source)
This removes the base directory from the header name, ensuring that the files are extracted without the directory structure.
The modified code would look like this:
import ( "archive/zip" "fmt" "io" "os" "path/filepath" ) func Zipit(source, target string) error { zipfile, err := os.Create(target) if err != nil { return err } defer zipfile.Close() archive := zip.NewWriter(zipfile) defer archive.Close() info, err := os.Stat(source) if err != nil { return nil } filepath.Walk(source, func(path string, info os.FileInfo, err error) error { if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } if info.IsDir() { header.Name = "/" } else { header.Method = zip.Deflate } writer, err := archive.CreateHeader(header) if err != nil { return err } if info.IsDir() { return nil } file, err := os.Open(path) if err != nil { return err } defer file.Close() _, err = io.Copy(writer, file) return err }) return err } func main() { err := Zipit("path/dir1" "/", "test" ".zip") if err != nil { fmt.Println(err) } }
This code effectively zips the content within the "dir1" directory without including the directory itself in the ZIP file.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3