一、wxml文件
<text>上傳圖片</text> <view> <button bindtap="uploadimg">點擊選擇上傳圖</button> </view> <image src='{{source}}' style='width:600rpx; height:600rpx' />
二、js文件
Page({
/**
* 頁面的初始數據
*/
data: {
//初始化為空
source:''
},
/**
* 上傳圖片
*/
uploadimg:function(){
var that = this;
wx.chooseImage({ //從本地相冊選擇圖片或使用相機拍照
count: 1, // 默認9
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
success:function(res){
//console.log(res)
//前台顯示
that.setData({
source: res.tempFilePaths
})
// 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://www.website.com/home/api/uploadimg',
filePath: tempFilePaths[0],
name: 'file',
success:function(res){
//打印
console.log(res.data)
}
})
}
})
},
)}
三、PHP后端代碼
// 上傳圖片 public function uploadimg() { $file = request()->file('file'); if ($file) { $info = $file->move('public/upload/weixin/'); if ($info) { $file = $info->getSaveName(); $res = ['errCode'=>0,'errMsg'=>'圖片上傳成功','file'=>$file]; return json($res); } } }
運行結果:
console打印結果:
此時表示上傳成功!