1

I have a front-end written in Vue and a backend written in Golang. I'm using Google app engine to run my backend service, and use gcloud datastore and gcloud storage to store the data and image that were submitted through front-end form.

I've been trying to upload an image using POST method. I convert the image to a base64 string. Then I add the data string to formdata and POST to my backend service. I keep getting empty form value in Go program. Is there a reason that Go cannot read base64 string, or I miss something important about FormData? Any help helps, thank you.

My front-end code:

var myForm = document.getElementById('myForm')
var formData = new FormData(myForm)

var imgBase64 = getBase64(//image-url//)
imgBase64.then(function (res) {
   formData.append('image', res)
}

axios.post(' //go-app-engine-service// ', formData)
.then(res => {
   console.log(res)
 })
.catch(error => {
   console.log(error)
 })

function getBase64(url) {
   return axios
     .get(url, {
        responseType: 'arraybuffer'
     })
     .then(response => Buffer.from(response.data, 'binary').toString('base64'))}

My Go code:

imgString := r.FormValue("image")
fmt.Printf("imgstring: %s, %d, %T\n", imgString, len(imgString), imgString) //=> getting empty imgString
nobsoph
  • 23
  • 6
  • 1
    You need to call r.ParseForm() to populate the form before you can access the FormValue. – dgm Jul 12 '18 at 23:25
  • @dgm According to [the docs](https://godoc.org/net/http#Request.FormValue): `FormValue calls ParseMultipartForm and ParseForm if necessary`. – Jofre Jul 13 '18 at 12:21
  • Go code looks good to me. I would say that error comes from the vue.js code. Can you check if the image gets converted to base64 before calling the backend? I saw this [question](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript) that may be of help . – Iñigo Jul 13 '18 at 14:20
  • @Iñigo the problem does come from front-end. function getBase64 returns the base64 string. I print out the formdata and found the line formData.append('image', res) doesn't work. there's no image and base64 get stored. not sure what's the problem but I will keep trying. – nobsoph Jul 16 '18 at 17:30

1 Answers1

0

Ok, after some research I realize the "scope" issue. function getBase64 returns a Promise and have to handle the value inside the scope, so I move the axios.post in the Promise and I finally see the base64 value in Go program. Problem solved.

modified front-end code:

var myForm = document.getElementById('myForm')
var formData = new FormData(myForm)

var imgBase64 = getBase64(//image-url//)
imgBase64.then(function (res) {
   formData.append('image', res)

   axios.post(' //go-app-engine-service// ', formData)
     .then(res => {
        console.log(res)
     })
     .catch(error => {
        console.log(error)
     })
}
nobsoph
  • 23
  • 6