Uploading and saving a zip file in golang

1,435 views
Skip to first unread message

mail2ar...@gmail.com

unread,
Sep 16, 2013, 6:54:24 AM9/16/13
to golan...@googlegroups.com

 Hi,

 I'm a newbie to golang and trying a write small utility for my project. I have to upload a zip file to a location, but i couldn't figure out how to read the uploaded file. Code snippet below,

 client.go

  filename := "/home/User/Tracker_Aug8.zip"
    file, err := os.Open(filename)

    if err != nil {
        fmt.Println("error: ", err)
    }

    defer file.Close()

    body_buf := bytes.NewBufferString("")
    body_writer := multipart.NewWriter(body_buf)

    file_writer, err := body_writer.CreateFormFile("zfile", filename)
    content_type := body_writer.FormDataContentType()
    body_writer.WriteField("pathToUpload", "/home/User/projects")
   _, err = io.Copy(file_writer, file)
//   err = body_writer.Close()
  http.Post("http://localhost:4000/upload", content_type, body_buf)

server.go

//skipped other codes

http.Handle("/upload", http.HandlerFunc(uploadHandler))

func uploadHandler(w http.ResponseWriter, r *http.Request) {
 err := r.ParseMultipartForm(2048)
    if err == nil {
        form := r.MultipartForm
        if form == nil {
            fmt.Println("no files to upload")
        } else {
            defer form.RemoveAll()

            fmt.Printf("%d files", len(form.File))    //prints 1 files
            osFile, err := os.Create("/home/User/projects/Tracker_Aug8.zip")
            if err != nil {
                panic(err.Error())
            }
            defer osFile.Close()
            formFile, _, err := r.FormFile("zfile")
            fmt.Println(formFile)
            if err != nil {
                fmt.Println(err)
            }

            defer formFile.Close()
            count, err := io.Copy(osFile, formFile)  //not copying the content
            if err != nil {
                panic(err.Error())
            }
            fmt.Println(count)
        }
    } else {
     
        fmt.Println(err.Error())
    }
}

Printing request

&{POST /upload HTTP/1.1 1 1 map[User-Agent:[Go 1.1 package http] Content-Length:[332] Content-Type:[multipart/form-data; boundary=9a316967e6878cb406685923ecf871c8dfd73e0db6566930c0f1926eb398] Accept-Encoding:[gzip]] 0xc20009f8c0 332 [] false localhost:4000 map[] map[] <nil> map[] 127.0.0.1:45510 /upload <nil>}

I'm getting a empty file in the specified location. What i'm doing wrong here ?

Thanks,
Arun
Reply all
Reply to author
Forward
0 new messages