微信小程式圖片選擇、上傳到伺服器、預覽(PHP)實現例項
阿新 • • 發佈:2019-01-02
微信小程式圖片選擇、上傳到伺服器、預覽(PHP)實現例項
小程式實現選擇圖片、預覽圖片、上傳到開發者伺服器上
後臺使用的tp3.2 圖片上傳
請求時候的header參考時可以去掉(個人後臺驗證許可權使用)
小程式前端程式碼:
<view class="section">
<form bindsubmit="bindFormSubmit">
<textarea placeholder="請輸入問題內容" name="content"/>
<view class="">
選擇提問圖片: <label bindtap="checkimg" >點選選擇圖片</label>
</view>
<view class="">
<image wx:for="{{imglist}}" mode="aspectFit" bindtap="ylimg" data-src="{{item}}" width:75px;height:75px;" src="{{item}}"></image>
</view>
<button form-type="submit"> 提交 </button>
</form>
</view>
小程式js程式碼:
data: {
imglist:[]
},
/**
* form提交事件
*/
bindFormSubmit:function(e){
self=this
//圖片
var imglist = self.data.imglist
//提問內容
var content=e.detail.value.content;
if(content==''){
wx.showToast({
title: '內容不能為空',
icon: 'loading',
duration: 1000,
mask:true
})
}
wx.showLoading({
title: '正在提交...',
mask:true
})
//新增問題
wx.request({
url: 'https://xxxxxxxxxx/index.PHP?g=user&m=center&a=createwt',
data: {
content:content
},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: app.globalData.header, // 設定請求的 header
success: function (res) {
// success
if(typeof(res.data)=='number'){
if (imglist != '') {
//開始插入圖片
for(var i=0;i<imglist.length;i++){
//上傳至伺服器
wx.uploadFile({
url: 'https://xxxxxxxx/index.php?g=user&m=center&a=upload', //僅為示例,非真實的介面地址
filePath: imglist[0],
name: 'files',
formData: {
'wtid': res.data
},
header: app.globalData.header,
success: function (res) {
if(i>=imglist.length){
self.setData({
imglist:[]
})
wx.hideLoading();
wx.showToast({
title: '提問成功',
icon: 'success',
duration: 2000,
mask: true
})
wx.navigateBack({
delta: 1
})
}
}
})
}
console.log(imglist);
}else{
wx.hideLoading();
wx.showToast({
title: '提問成功',
icon: 'success',
duration: 2000,
mask: true
})
wx.navigateBack({
delta: 1
})
}
}else{
wx.hideLoading();
wx.showToast({
title: res.data,
icon: 'loading',
duration: 1000,
mask: true
})
}
},
fail: function (res) {
self.onLoad();
}
})
},
//點選選擇圖片
checkimg:function(){
console.log('點選選擇圖片');
self=this
wx.chooseImage({
count: 9, // 預設9
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
success: function (res) {
// 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
var tempFilePaths = res.tempFilePaths
self.setData({
imglist:tempFilePaths
})
}
})
},
//點選預覽圖片
ylimg:function(e){
wx.previewImage({
current: e.target.dataset.src,
urls: this.data.imglist // 需要預覽的圖片http連結列表
})
}
php後臺程式碼
//圖片上傳
public function upload(){
if(IS_POST){
$upload = new \Think\Upload();// 例項化上傳類
$upload->maxSize = 3145728 ;// 設定附件上傳大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳型別
$upload->rootPath = './Uploads/'; // 設定附件上傳根目錄
$upload->savePath = ''; // 設定附件上傳(子)目錄
// 上傳檔案
$info = $upload->upload();
if(!$info) {// 上傳錯誤提示錯誤資訊
$this->error($upload->getError());
}else{// 上傳成功 獲取上傳檔案資訊
//插入到資料庫中
}
}
}