小程序端代码:
// 上传图片
uploadImage() {
var that = this
let url = 'https://www.kwaili.com:8001/appfls/uploadimage'
let list = this.data.list
for(let i=0; i<list.length; i++) {
let filePth = list[i].tempFilePath
let uploadStatus = 'list['+i+'].uploadStatus'
wx.uploadFile({
url: url,
filePath: filePth,
name: 'photo',
formData: {
'openid': that.data.openid
},
success (res){
console.log('wx.uploadFile success', i)
if(res.statusCode!=200) {
console.error('upload file failure', i, res)
return
}
// 上传结果
let result = JSON.parse(res.data)
if(result.status==1) {
console.log('upload file success', i, result)
that.setData({
[uploadStatus]: 1,
})
}else {
console.error('upload file error', i, result)
that.setData({
[uploadStatus]: -1,
})
}
},
fail(err) {
console.error('wx.uploadFile failure', i, err)
that.setData({
[uploadStatus]: 0,
})
},
complete(res) {
console.log('wx.uploadFile complete', i)
// 全部上传则保存数据
if(that.uploadAllComplete()) {
that.saveShare()
}
}
})
}
},
服务器端代码:
# 微信上传图片
@app.route('/appfls/uploadimage', methods=['POST'])
def appflsuploadimage():
if request.method == 'POST' and 'photo' in request.files:
try:
# 上传文件夹
ym = time.strftime('%Y%m',time.localtime())
openid = request.form['openid']
folder= os.path.join(ym, openid)
# 新文件名
photo = request.files['photo']
suffix = photo.filename.split(".")[1]
uid = str(uuid.uuid4())
suid = ''.join(uid.split('-'))
newfilename = suid +'.'+ suffix
# 保存文件
uploaded_file_name = photos.save(photo, folder=folder, name=newfilename)
# 静态文件路径
static_file_path = os.path.join(photo_upload_path,folder,newfilename)
except Exception as e:
return {'status':-2, 'message':'upload error', 'exception':str(e)}
else:
return {'status':1, 'message':'upload success', 'static_file_path':static_file_path}
else:
return {'status':-1, 'message':'post request not allow'}
flask_uploads 相关配置
# 上传图片,配置参数使用UPLOADED_ + UploadSet.name + _DEST形式
photos = UploadSet('PHOTO') # 上传图片类
photo_upload_path = os.path.join('static','upload','appfls')
app.config['UPLOADED_PHOTO_DEST'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), photo_upload_path) # 上传图片保存的目录
IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())
app.config['UPLOADED_PHOTO_ALLOW'] = IMAGES # 允许上传的图片类型,其他类型不允许
configure_uploads(app, photos) # 初始化配置
网友评论