微信小程序上传照片+golang后台 demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Programmer_FuQiang/article/details/84837789

wxml部分

<view class='mainView' bindtap='chooseImage'>

<image class="imageClass" src="{{userHeaderImage}}"></image>

</view>

js部分

Page({

/**

* 页面的初始数据

*/

data: {

userHeaderImage: "../../image/dachenglogo.jpg"

},

/**

* 生命周期函数--监听页面加载

*/

onLoad: function (options) {

},

chooseImage: function () {

var that = this;

wx.chooseImage({

count: 1,

sizeType: ['original', 'compressed'],

sourceType: ['album', 'camera'],

success(res) {

// tempFilePath可以作为img标签的src属性显示图片

const tempFilePaths = res.tempFilePaths[0]

that.setData({

userHeaderImage: tempFilePaths

})

console.log(tempFilePaths)

//上传图片

wx.uploadFile({

url: 'http://localhost:8080/uppphoto', //仅为示例,非真实的接口地址

filePath: tempFilePaths,

name: 'file',

header: {

//'content-type': 'application/json'

//application/x-www-form-urlencoded;

'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'

},

method: 'POST',

formData: {

'userId': 10001

},

success(res) {

const data = res.data

console.log(res);

//do something

}

})

}

})

},

})

golang后台

首先你的注册路由我用的是beego框架

beego.Router("/uppphoto", &controllers.UppphotoController{})//这个是我用beego注册的路由!!!!!
 

package controllers
//上传图片
import (
    "order/models"
    "fmt"
    "github.com/astaxie/beego"
    "encoding/json"

)

type UppphotoController struct {
    beego.Controller
}

func (c *UppphotoController) Post() {

        f, h, ere := c.GetFile("file") //获取上传的文件 myfile
        fmt.Println("f==",f)
        fmt.Println("f==",ere)

        pathname := h.Filename
        fmt.Println("uuuuuuu=====", pathname)
        fmt.Println("图片名称", pathname)
        path := "./static/uploadout/" + pathname //图片目录+图片名称
        fmt.Println("path===",path)
        f.Close()                                //关闭上传的文件,不然的话会出现临时文件不能清除的情况
        c.SaveToFile("file", path)          //存文件

}

主要上面红色的部分,

f, h, ere := c.GetFile("file")

c.SaveToFile("file", path)

注意上面的!!!!这两个!!!一定要一直否则失败!!

猜你喜欢

转载自blog.csdn.net/Programmer_FuQiang/article/details/84837789