How to Zip Directory Contents Excluding Root Folder
Question:
You have a directory structure like this:
dir1 file1.html file2.go
When you zip it to dir1.zip and extract it, you get the same structure:
dir1 file1.html file2.go
However, you want to zip the content inside "dir1" without the root folder "dir1" as a result after extracting.
Answer:
To achieve this, modify the code in your Zipit function. Specifically, examine the following code:
if baseDir != "" { header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) }
This code adds the base directory (in this case, "dir1") to the filename inside the archive. To exclude the root folder from the extracted content, simply remove the addition of the base directory:
header.Name = strings.TrimPrefix(path, source)
This code trims the prefix from the path and assigns it to the header name without including the base directory.
Example:
If you're calling your function as follows:
Zipit("dir1/", "dir1.zip")
After making the code modification, your extracted content will be:
file1.html file2.go
without the "dir1" root folder.
Other Notes:
The above is the detailed content of How to Zip Directory Contents Excluding the Root Folder?. For more information, please follow other related articles on the PHP Chinese website!