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 } ... })
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!