【问题标题】:flask jquery html form returning None for Image烧瓶 jquery html 表单为图像返回 None
【发布时间】:2021-03-30 16:43:09
【问题描述】:

Web 开发新手,尝试简单上传图片,目标是进入 s3。但是目前当我选择一张照片并提交请求时返回为无,无法弄清楚原因。

html 表单

<form name="update_profile_image_form" id="update_profile_image_form" class="text-center mt-2" method="POST" enctype="multipart/form-data" style="display: block;" action="/user/update/profile-image/">
  <input type="file" class="form-control-file form-control-file-sm ml-3 mt-2" id="profile_image" name="profile_image" accept="image/*">
  <input type="submit" value="Update" class="form-control-file form-control-file-sm ml-2 mt-2 text-center btn btn-sm btn-info" style="width: 90%;"></input>
</form>

脚本

$("form[name=update_profile_image_form").submit(function(e) {

  var $form = $(this);
  var $error = $form.find(".error");
  var data = $form.serialize();

  $.ajax({
      url: "/user/update/profile_image",
      type: "POST",
      data: data,
      dataType: "json",
      success: function(resp) {
        window.location.href = "/account/";
        
      }
    });
  
    e.preventDefault();
  });

路线

@app.route('/user/update/profile_image', methods=['POST'])
def update_profile_image(): 
  return User().update_profile_image()

功能

  def update_profile_image(self):
    img = request.files.get('profile_image')
    print(img)
    
    return redirect(url_for('account'))

也试过img = request.form.get('profile_image')

没有错误,print(img) 返回为无

目标是上传图片,传递给函数,为其分配一个uuid并上传到s3,提前谢谢大家!

【问题讨论】:

    标签: python api flask file-upload python-requests


    【解决方案1】:

    您不能序列化图像并将其作为 json 发送。

    您应该使用form data object。但是,print(img) 将不起作用,因为您无法以这种方式打印图像。

    或者,您可以通过converting it to base64 将图像作为字符串传递。

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多