效果圖如下:
wxml:
<view class="container">
<image class="image" src="{{imgPath}}" mode='scaleToFill' bindtap="previewImg"></image>
<button bindtap="selectImg">選擇圖片</button>
<button bindtap="loadImg">上傳圖片</button>
</view>
圖片選擇
wx.chooseImage(object)
從相冊中選擇圖片或是使用拍照
參數 | 類型 | 必填 | 說明 |
---|---|---|---|
count | Number | 否 | 最多可選擇圖片數量,默認9 |
sizeType | StringArray | 否 | original:原圖;compressed:壓縮圖;默認兩者都有 |
sourceType | StringArray | 否 | album:從相冊選擇;camera:相機拍攝;默認兩者都有 |
success | Function | 是 | 成功返回回調函數 |
fail | Function | 否 | 失敗回調函數 |
complate | Function | 否 | 完成回調函數 |
selectImg: function () {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
//res.tempFilePaths 返回圖片本地文件路徑列表
var tempFilePaths = res.tempFilePaths;
that.setData({
imgPath: tempFilePaths[0]
})
}
})
}
圖片預覽
wx.previewImage(object)
預覽圖片
參數 | 類型 | 必填 | 說明 |
---|---|---|---|
current | String | 否 | 當前顯示圖片鏈接,不填默認urls第一張 |
urls | StringArray | 是 | 需要預覽的圖片鏈接列表 |
success | Function | 否 | 成功返回回調函數 |
fail | Function | 否 | 失敗回調函數 |
complete | Function | 否 | 完成回調函數 |
previewImg: function (e) {
var img = this.data.imgPath;
// 設置預覽圖片路徑
wx.previewImage({
current: img,
urls: [img]
})
}
圖片上傳
使用很早之前以前的JFinal上傳
時用的后端接口
loadImg: function () {
var that = this;
wx.uploadFile({
url: "http://localhost:8080/upload/upload",
filePath: that.data.imgPath,
name: "upload_file",
// 請求攜帶的額外form data
/*formData: {
"id": id
},*/
header: {
'Content-Type': "multipart/form-data"
},
success: function (res) {
wx.showToast({
title: "圖像上傳成功!",
icon: "",
duration: 1500,
mask: true
});
},
fail: function (res) {
wx.showToast({
title: "上傳失敗,請檢查網絡或稍后重試。",
icon: "none",
duration: 1500,
mask: true
});
}
})
}