向服务器发送base64字符串数据,但接收空的表单值



我有一个用Vue编写的前端和一个用Golang编写的后端。我使用谷歌应用程序引擎来运行我的后端服务,并使用gcloud数据存储和gcloud存储来存储通过前端表单提交的数据和图像。

我一直在尝试使用POST方法上传图像。我将图像转换为base64字符串。然后,我将数据字符串添加到formdata,并将POST添加到后端服务。我在Go程序中不断得到表单值。Go无法读取base64字符串,或者我遗漏了FormData的一些重要内容,这是有原因的吗?任何帮助都有帮助,谢谢。

我的前端代码:

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'))}

我的Go代码:

imgString := r.FormValue("image")
fmt.Printf("imgstring: %s, %d, %Tn", imgString, len(imgString), imgString) //=> getting empty imgString

好的,经过一些研究,我意识到了"范围"问题。函数getBase64返回一个Promise,并且必须处理范围内的值,所以我在Promise中移动axios.post,最后在Go程序中看到base64值。问题解决了。

修改的前端代码:

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)
})
}

最新更新