0.页面展示效果
1)首先房东填写房屋信息;
2)当房东填写发布的房源信息之后,隐藏(hide)刚才填写信息的界面,同时显示(show)上传房屋图片的界面。
1.后端代码
@api.route("/houses/image", methods=["POST"])
@login_required
def save_house_image():"""保存房屋的图片参数 图片 房屋的id"""image_file = request.files.get("house_image")house_id = request.form.get("house_id")if not all([image_file, house_id]):return jsonify(errno=RET.PARAMERR, errmsg="参数错误")# 判断house_id正确性try:house = House.query.get(house_id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="数据库异常")if house is None: # if not house:return jsonify(errno=RET.NODATA, errmsg="房屋不存在")image_data = image_file.read()# 保存图片到七牛中try:file_name = storage(image_data)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.THIRDERR, errmsg="保存图片失败")# 保存图片信息到数据库中house_image = HouseImage(house_id=house_id, url=file_name)db.session.add(house_image)# 处理房屋的主图片if not house.index_image_url:house.index_image_url = file_namedb.session.add(house)try:db.session.commit()except Exception as e:current_app.logger.error(e)db.session.rollback()return jsonify(errno=RET.DBERR, errmsg="保存图片数据异常")image_url = constants.QINIU_URL_DOMAIN + file_namereturn jsonify(errno=RET.OK, errmsg="OK", data={"image_url": image_url})
2.前端html代码
<form id="form-house-image" action="/api/house/image" method="post" enctype="multipart/form-data"><input type="hidden" name="house_id" id="house-id" value=""><li><div class="house-title"><h3>添加图片</h3></div><div class="house-content"><div class="house-image-cons"></div><div class="form-group"><label for="house-image">选择图片</label><input type="file" accept="image/*" name="house_image" id="house-image"></div><input type="submit" class="btn btn-success" value="上传"></div></li></form>
3.前端js代码
$("#form-house-image").submit(function (e) {e.preventDefault();$(this).ajaxSubmit({url: "/api/v1.0/houses/image",type: "post",dataType: "json",headers: {"X-CSRFToken": getCookie("csrf_token"),},success: function (resp) {if (resp.errno == "4101") {location.href = "/login.html";} else if (resp.errno == "0") {$(".house-image-cons").append('<img src="' + resp.data.image_url +'">');} else {alert(resp.errmsg);}}})})