1. 压缩解压文件

    1.1.2. 解压文件

    1. import (
    2. "archive/zip"
    3. "fmt"
    4. "io"
    5. "log"
    6. "os"
    7. "path/filepath"
    8. "strings"
    9. )
    10. func main() {
    11. files, err := Unzip("done.zip", "output-folder")
    12. if err != nil {
    13. log.Fatal(err)
    14. }
    15. fmt.Println("Unzipped:\n" + strings.Join(files, "\n"))
    16. }
    17. // Unzip will decompress a zip archive, moving all files and folders
    18. // within the zip file (parameter 1) to an output directory (parameter 2).
    19. r, err := zip.OpenReader(src)
    20. if err != nil {
    21. return filenames, err
    22. }
    23. defer r.Close()
    24. for _, f := range r.File {
    25. // Store filename/path for returning and using later on
    26. fpath := filepath.Join(dest, f.Name)
    27. // Check for ZipSlip. More Info: http://bit.ly/2MsjAWE
    28. if !strings.HasPrefix(fpath, filepath.Clean(dest)+string(os.PathSeparator)) {
    29. return filenames, fmt.Errorf("%s: illegal file path", fpath)
    30. }
    31. filenames = append(filenames, fpath)
    32. if f.FileInfo().IsDir() {
    33. // Make Folder
    34. os.MkdirAll(fpath, os.ModePerm)
    35. continue
    36. }
    37. if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
    38. return filenames, err
    39. }
    40. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
    41. if err != nil {
    42. return filenames, err
    43. }
    44. rc, err := f.Open()
    45. if err != nil {
    46. return filenames, err
    47. }
    48. _, err = io.Copy(outFile, rc)
    49. // Close the file without defer to close before next iteration of loop
    50. outFile.Close()
    51. rc.Close()
    52. if err != nil {
    53. return filenames, err
    54. }
    55. }
    56. return filenames, nil