Chrest Koo
Chrest Koo

Reputation: 41

Handle Http Upload Zip file in Golang

I'm using golang net/http package to retrieve the uploaded zip file via postman. The attachment file link. It is not dangerous file. Feel free to check out.

Development env

Code to capture the post form transSourceFile file.

func HandleFileReqTest(w http.ResponseWriter, req *http.Request, params map[string]string) err {

    if err := req.ParseMultipartForm(32 << 20); err != nil {
       return err
    }

    file, header, err := req.FormFile("transSourceFile")
    if err != nil {
       return err
    }
    defer file.Close()
    fmt.Println("header.Size:", header.Size)
    return nil
}

I tried below code also no use

func HandleFileReqTest(w http.ResponseWriter, req *http.Request, params map[string]string) err {
    if err := req.ParseForm(); err != nil {
        return err
    }
    req.ParseMultipartForm(32 << 20)
    file, header, err := req.FormFile("transSourceFile")
    if err != nil {
        return err
    }
    defer file.Close()
    fmt.Println("header.Size:", header.Size)
    return nil
}

Result: Local machine got the same file size as the origin file. Server with golang:1.17.5-stretch got the different file size compare to origin file.

As the result on this, i'm unable to unzip the file in the server. Anyone can help?

Upvotes: 3

Views: 1080

Answers (2)

Ashutosh Singh
Ashutosh Singh

Reputation: 1047

Data isn't being flushed to the file completely. You should close the file first to ensure that the data is fully flushed.

  // create a local file filename
    dst, err := os.Create("filename.zip")

      // save it
     fl, err = io.Copy(dst, src)

     // Close the file
     dst.Close()

     stat, _ := dst.Stat()

 //Now check the size stat.Size() or header.Size after flushing the file.

Upvotes: 0

serge-v
serge-v

Reputation: 780

You need to copy form file to the actual file:

f, err := os.Create("some.zip")
defer f.Close()
n, err := io.Copy(f, file)

Upvotes: 2

Related Questions