将base64字符串数据发送到服务器,但接收到空表格值

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
", imgString, len(imgString), imgString) //=> getting empty imgString
drf21989
drf21989 问题确实来自前端。函数getBase64返回base64字符串。我打印出formdata,发现formData.append('image',res)行不起作用。没有图像,并且存储了base64。不知道是什么问题,但我会继续尝试。
大约 2 年之前 回复
dongshi6969
dongshi6969 Go代码对我来说看起来不错。我会说错误来自vue.js代码。您可以在调用后端之前检查图像是否已转换为base64吗?我看到这个问题可能会有所帮助。
大约 2 年之前 回复
dpygo62420
dpygo62420 根据文档:FormValue在必要时调用ParseMultipartForm和ParseForm。
大约 2 年之前 回复
duangejian6657
duangejian6657 您需要调用r.ParseForm()来填充表单,然后才能访问FormValue。
大约 2 年之前 回复

1个回答

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)
     })
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐