1、上傳圖片到服務(wù)器,有兩個步驟:
? ? 1.1? 拿到可上傳的圖片?wx.chooseImage
????1.2? 將圖片上傳到服務(wù)器??wx.uploadFile
2、代碼實現(xiàn)
<button?bindtap="upload">點擊上傳</button>文章來源:http://www.zghlxwxcb.cn/news/detail-520050.html
<image?src="{{imgPath}}"?mode=""/>文章來源地址http://www.zghlxwxcb.cn/news/detail-520050.html
upload(){
var _this=this
wx.chooseImage({
拿幾張圖片 count
圖片上傳類型 sizeType
圖片來源 sourceType
success(res){//獲取成功
wx.uploadFile({
臨時圖片路徑 filePath
服務(wù)器地址 url
name
timeout
success(res){
let imgPath=baseUrl+JSON.parse(res2.data).data
_this.setData({
imgPath
})
}
})
}
})
}
// 上傳圖片到服務(wù)器
upload() {
var _this=this
wx.chooseImage({
count: 1, //可上傳的圖片數(shù)量
sizeType: ['original', 'compressed'],//上傳圖片類型:原圖、壓縮圖
sourceType: ['album', 'camera'], //圖片來源:相冊、照相機
success(res) {
// 成功,將圖片上傳到服務(wù)器
console.log(res);
// 拿取臨時路徑文件
let filePath = res.tempFilePaths[0]
/*
控制臺的 tempFilePaths: ["http://tmp/DTalF29Fe4wkc6221b571e512fe6b7a68b2926e81b51.jpg"]
即表示圖片的臨時路徑
*/
wx.uploadFile({
/* // 拿到臨時圖片路徑后上傳到服務(wù)器,服務(wù)器將返回一個公網(wǎng)地址,
屆時在任意角落都將能訪問到這張圖片 */
filePath: filePath, //臨時文件路徑
url: baseUrl + "/api/test/user/upload", //填寫公司的服務(wù)器地址
name: 'file', /* //非常重要!?。?!是后臺訪問二進制數(shù)據(jù)的關(guān)鍵
該 file 是對應(yīng)接口,所需要傳遞的參數(shù) */
timeout:5000,
success(res2){
console.log(res2);
// 需解析信息,拿到圖片路徑,因為本項目的 域名以 .com 結(jié)尾,所以需要“ / ”進行必要分隔
let imgPath=baseUrl+"/"+JSON.parse(res2.data).data //將二進制轉(zhuǎn)換成字符串類型
_this.setData({
imgPath
})
}
})
}
})
},
到了這里,關(guān)于13、微信小程序:上傳圖片到服務(wù)器的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!