drhanjuw56233 2018-07-12 21:51
浏览 263

将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
  • 写回答

1条回答 默认 最新

  • doubo3384 2018-07-16 18:12
    关注

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘