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)) ... }
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))
with:
header.Name = strings.TrimPrefix(path, source)
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 } ... })
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