【问题标题】:send base64 string data to server but receive empty form value将 base64 字符串数据发送到服务器但收到空表单值
【发布时间】:2018-07-12 21:51:41
【问题描述】:

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

我一直在尝试使用 POST 方法上传图片。我将图像转换为 base64 字符串。然后我将数据字符串添加到 formdata 并 POST 到我的后端服务。我在 Go 程序中不断获得 empty 表单值。 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, %T\n", imgString, len(imgString), imgString) //=> getting empty imgString

【问题讨论】:

  • 您需要调用 r.ParseForm() 来填充表单,然后才能访问 FormValue。
  • @dgm 根据the docs: FormValue calls ParseMultipartForm and ParseForm if necessary.
  • Go 代码对我来说看起来不错。我会说错误来自 vue.js 代码。你能在调用后端之前检查图像是否被转换为base64吗?我看到了这个 question 可能会有所帮助。
  • @Iñigo 问题确实来自前端。函数 getBase64 返回 base64 字符串。我打印出表单数据,发现行 formData.append('image', res) 不起作用。没有图像,base64 被存储。不知道是什么问题,但我会继续努力。

标签: google-app-engine go vue.js axios


【解决方案1】:

好的,经过一些研究,我意识到“范围”问题。 函数 getBase64 返回一个 Promise 并且必须处理范围内的值,所以我将 axios.post 移动到 Promise 中,我终于在 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)
     })
}

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多