微信小程式post請求Python Flask資料
阿新 • • 發佈:2018-12-21
1、微信小程式端:
(1)index.js
//index.js //獲取應用例項 const app = getApp() Page({ data: { motto: '檢測結果:', value: '0', userInfo: {}, hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo'), userImage: "/images/jia.png", img_arr: [], }, //事件處理函式 bindViewTap: function() { var that = this //!!!!!!!!!“搭橋” //利用API從本地讀取一張圖片 wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: function (res) { var tempFilePaths = res.tempFilePaths //將讀取的圖片替換之前的圖片 that.setData( { userImage: tempFilePaths[0], img_arr: that.data.img_arr.concat(tempFilePaths[0]), } )//通過that訪問 console.log(that.data.userImage) } }) }, changeName: function (e) { this.setData({ value: "xiao", }) }, upload: function () { var that = this wx.uploadFile({ url: 'http://127.0.0.1:8090/postdata', // filePath: that.data.img_arr[0], filePath: that.data.userImage, name: 'content', // formData: adds, success: function (res) { console.log(res.data); that.setData({ value: JSON.parse(res.data)['value'], userImage: JSON.parse(res.data)['resurl'] }) if (res) { wx.showToast({ title: '檢測完成!', duration: 3000 }); } } }) this.setData({ formdata: '' }) }, takePhoto() { var that = this wx.chooseImage({ count: 1, // 預設9 sizeType: ['original', 'compressed'], sourceType: ['camera'], success: function (res) { var tempFilePaths = res.tempFilePaths that.setData( { userImage: res.tempFilePaths[0], }) console.log("res.tempImagePath" + tempFilePaths[0]) } }) }, onLoad: function () { if (app.globalData.userInfo) { this.setData({ userInfo: app.globalData.userInfo, hasUserInfo: true }) } else if (this.data.canIUse){ // 由於 getUserInfo 是網路請求,可能會在 Page.onLoad 之後才返回 // 所以此處加入 callback 以防止這種情況 app.userInfoReadyCallback = res => { this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } } else { // 在沒有 open-type=getUserInfo 版本的相容處理 wx.getUserInfo({ success: res => { app.globalData.userInfo = res.userInfo this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) } }, getUserInfo: function(e) { console.log(e) app.globalData.userInfo = e.detail.userInfo this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true }) } })
(2)index.wxml
<!--index.wxml--> <view class="container"> <view class='imagesize'> <image src='{{userImage}}'></image> </view> <view class="usermotto"> <text>{{motto}}</text> <text>{{value}}</text> </view> <view class='userbtn'> <button bindtap='bindViewTap'>選擇影象</button> <button bindtap="takePhoto">相機拍照</button> <button bindtap="upload"> 開始檢測 </button> </view> </view>
(3)index.wxss
/**index.wxss**/ .imagesize{ display:flex; width:100%; height: 800rpx; justify-content: center; } .imagesize image { width:90%; height: 800rpx; } .usermotto { width:100%; height: 50rpx; text-align: left; margin-top: 100px; } .userbtn { display:flex; width: 92%; margin-top: 20rpx; justify-content: center; } .userbtn button { background-color: #ff8719; color: white; border-radius: 25rpx; }
2、Python Flask端
from flask import Flask
from flask import request
import json
import os
import uuid
import cv2
app = Flask(__name__)
@app.route("/")
def index():
return "Hello"
resSets = {}
@app.route('/postdata', methods=['POST'])
def postdata():
f = request.files['content']
user_input = request.form.get("name")
basepath = os.path.dirname(__file__) # 當前檔案所在路徑
src_imgname = str(uuid.uuid1()) + ".jpg"
upload_path = os.path.join(basepath, 'static/srcImg/')
if os.path.exists(upload_path)==False:
os.makedirs(upload_path)
f.save(upload_path + src_imgname)
im = cv2.imread(upload_path + src_imgname, 0)
save_path = os.path.join(basepath, 'static/resImg/')
if os.path.exists(save_path) == False:
os.makedirs(save_path)
save_imgname = str(uuid.uuid1()) + ".jpg"
cv2.imwrite(save_path + save_imgname, im)
resSets["value"] = 10
resSets["resurl"] = "http://127.0.0.1:8090" +'/static/resImg/' + save_imgname
return json.dumps(resSets, ensure_ascii=False)
if __name__=="__main__":
app.run(host="0.0.0.0", port=8090)
3、結果