Hello there,
I’m trying to extract a zip file, which has a series of folders and contents inside. Whenever I try this code, and no folders are present in the zip file, it works flawlessly. Thing is, I wanted to work with folders and it just doesn’t work no matter what.
// Create a reader out of the zip archive
zipReader, err := zip.OpenReader("test.zip")
if err != nil {
log.Fatal(err)
}
defer zipReader.Close()
// Iterate through each file/dir found in
for _, file := range zipReader.Reader.File {
// Open the file inside the zip archive
// like a normal file
zippedFile, err := file.Open()
if err != nil {
log.Fatal(err)
}
defer zippedFile.Close()
// Specify what the extracted file name should be.
// You can specify a full path or a prefix
// to move it to a different directory.
// In this case, we will extract the file from
// the zip to a file of the same name.
targetDir := "./"
extractedFilePath := filepath.Join(
targetDir,
file.Name,
)
// Extract the item (or create directory)
if file.FileInfo().IsDir() {
// Create directories to recreate directory
// structure inside the zip archive. Also
// preserves permissions
log.Println("Creating directory:", extractedFilePath)
os.MkdirAll(extractedFilePath, file.Mode())
} else {
// Extract regular file since not a directory
log.Println("Extracting file:", file.Name)
// Open an output file for writing
outputFile, err := os.OpenFile(
extractedFilePath,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
file.Mode(),
)
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
// "Extract" the file by copying zipped file
// contents to the output file
_, err = io.Copy(outputFile, zippedFile)
if err != nil {
log.Fatal(err)
}
}
}
Any suggestions? It returns folder/image.jpg no such file or directory
I’m new to go so sorry if this is a stupid question.