How to Zip Directory Contents Excluding the Root Folder?

Linda Hamilton
Release: 2024-11-18 22:17:02
Original
297 people have browsed it

How to Zip Directory Contents Excluding the Root Folder?

How to Zip Directory Contents Excluding Root Folder

Question:

You have a directory structure like this:

dir1
  file1.html
  file2.go
Copy after login
Copy after login

When you zip it to dir1.zip and extract it, you get the same structure:

dir1
  file1.html
  file2.go
Copy after login
Copy after login

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))
}
Copy after login

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)
Copy after login

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")
Copy after login

After making the code modification, your extracted content will be:

file1.html
file2.go
Copy after login

without the "dir1" root folder.

Other Notes:

  • It's worth noting that this modification affects the filename within the archive, not the actual content of the files.
  • You can experiment with other filepath functions to further customize the filename as desired.

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!

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