本例的服務(wù)器基于flask,配置flask可以參見[Flask]上傳多個(gè)文件到服務(wù)器https://blog.csdn.net/weixin_37878740/article/details/128435136?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170581653516800185854860%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=170581653516800185854860&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-5-128435136-null-null.nonecase&utm_term=flask&spm=1018.2226.3001.4450
一、上傳圖片
? ? ? ? 在這里使用POST協(xié)議將圖片上傳到服務(wù)器,服務(wù)器代碼為:
@app.route('/uploader', methods=['POST'])
def uploader():
i=0
for img in request.files.getlist('photo'):
suffix = '.' + img.filename.split('.')[-1] # 獲取文件后綴名
img_path = './static/uploads/' + str(int(time.time())) +'_p'+str(i) + suffix # 拼接路徑
img.save(img_path) #保存圖片
print(img_path)
i=i + 1 #序號(hào)戳記++
return {'msg':'ok'}
? ? ? ? 微信端代碼為:
postImg(e){
const that = this
//選擇圖片
wx.chooseImage({
count:1, //選擇張數(shù)
sizeType:['compressed'], //是否壓縮圖
sourceType:['album','camera'], //數(shù)據(jù)源
success(res){
let tempFilePath = res.tempFilePaths; //圖片的本地路徑
that.upload(that,tempFilePath); //上傳圖片
}
})
},
? ? ? ? 使用微信提供的wx.chooseImage選擇圖片,其中upload為單獨(dú)封裝的函數(shù),實(shí)質(zhì)上是一個(gè)Post函數(shù),如下:
//上傳函數(shù)
upload(page,path){
wx.showToast({
icon:'loading',
title: '正在上傳',
})
wx.uploadFile({
filePath: path[0],
name: 'photo',
url: '鏈接/uploader',
header: {"Content-Type": "multipart/form-data"},
//formData:{'session_token':wx.getStorageSync('session_token')}, //放置token
success(res)?{
console.log(res.data);},
fail(res){
console.log(res)}
})
},
? ? ? ? 需要注意的是,這個(gè)方法只會(huì)上傳第一張圖片,如果需要多張上傳,需要在let tempFilePath = res.tempFilePaths;處對(duì)圖片進(jìn)行循環(huán)解析
二、獲取圖片
? ? ? ? 其思路為:設(shè)置一個(gè)圖片路徑字符串變量,通過get指令讓其等于服務(wù)器中的圖片地址即可。
? ? ? ? flask端代碼為:
@app.route('/getImg',methods=['GET'])
def getImg():
idx = request.args.get("index",default=1,type=int) #參數(shù)名,默認(rèn)參數(shù),參數(shù)類型
ImgPath = 'static/src/{}.jpg'.format(idx)
return "{}".format(ImgPath)
? ? ? ? 微信端的代碼為:文章來源:http://www.zghlxwxcb.cn/news/detail-828383.html
getImg(e){
const that = this
????wx.request({
??????url:'鏈接',
??????method:'GET',
??????data:{
index:1,
??????},
??????success(res)?{
????????console.log(res.data);
????????that.setData({imgUrl:?'服務(wù)器絕對(duì)路徑/'+res.data?});
??????},
fail(res){
console.log(res)
}
????});??
??},
文章來源地址http://www.zghlxwxcb.cn/news/detail-828383.html
到了這里,關(guān)于[小程序]向服務(wù)器上傳圖片和從服務(wù)器下載圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!