How to upload a file using golang and ajax

11,778 views
Skip to first unread message

DEXTER

unread,
Feb 10, 2012, 9:37:59 PM2/10/12
to golang-nuts
Hi
How do I upload files using ajax and golang ?

Thanks
Dexter

Paddy Foran

unread,
Feb 10, 2012, 11:03:57 PM2/10/12
to DEXTER, golang-nuts
I think you're confused. AJAX is a Javascript technology. It doesn't really apply to Go. I think you probably want the http package, which will let you make HTTP requests.

Thanks,
Paddy Foran

GGGO

unread,
Feb 10, 2012, 11:15:06 PM2/10/12
to golang-nuts
You need a web server in Go :
package main

import (
"fmt"
"net/http"
"log"
"io/ioutil"
)

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
file, handler, err := req.FormFile("file")
if err != nil {
fmt.Println(err)
}
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
err = ioutil.WriteFile(handler.Filename, data, 0777)
if err != nil {
fmt.Println(err)
}
}

func main() {
http.HandleFunc("/upload", HelloServer)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

I don't have any example in ajax right now but a simple form in html
to post file :
<form enctype="multipart/form-data" action="http://localhost:8080/
upload" method="post">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>

With Ajax is the same process, you need a form in html and ajax to
post the form.

GGGO

DEXTER MCCONNELL

unread,
Feb 10, 2012, 11:24:13 PM2/10/12
to Paddy Foran, golang-nuts
Hi Thanks for your reply,
I could not find any working code for http package file upload, can you point me to a url with sample code

Thank you
Dexter
--
...at the entrance gate of Heaven!

Kyle Finley

unread,
Feb 10, 2012, 11:42:03 PM2/10/12
to golan...@googlegroups.com, Paddy Foran
jQuery File Upload has a Go backend build for Google App Engine:

Source:

Demo:

- Kyle

Daniel Theophanes

unread,
Feb 11, 2012, 1:37:28 AM2/11/12
to golan...@googlegroups.com
The following uploads via a normal POST, not an AJAX post, but that change isn't hard to make.
It is a complete self contained example of how to upload a file.  I find it a useful utility.

in main.go lines 239 - 356

-Daniel

Sourabh

unread,
Jul 26, 2016, 7:24:24 AM7/26/16
to golang-nuts
Nice code! I want to upload file from ios client to webserver. Any advice to extract image file information from client, so that it can be stored in server.
Reply all
Reply to author
Forward
0 new messages