How do i include an image file in json?
本问题已经有最佳答案,请猛点这里访问。
我目前正试图向我的flask restful服务发送一个post请求,该服务将生成一个模型以保存到数据库中。这个模型将包含一个通过Cloudinary托管的图像的URL,以及其他数据,如日期和名称。
我的问题是,在邮递员中,我只允许发送
我的问题是,如果只允许我发送一个或任意一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | from cloudinary.uploader import upload from cloudinary.utils import cloudinary_url from flask_restful import Resource from flask import request from models.image import ImageModel from schemas.image import ImageSchema image_schema = ImageSchema() image_list_schema = ImageSchema(many=True) class Image(Resource): @classmethod def post(cls): image_to_upload = request.files["image"] if image_to_upload: upload_result = upload(image_to_upload) url = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=100,height=100)[0] full_size_url = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=200, height=100, radius=20, effect="sepia")[0] image_json = request.get_json() # this returns None image_json["url"] = url image_json["full_size_url"] = full_size_url image = image_schema.load(image_json) try: image.save_to_db() except: return {"message":"error uploading file"} return image_schema.dump(image), 201 return {"message":"no image uploaded"}, 401 |
当您使用multipart/form数据将文件发送到flask时,该文件将是请求的.files,因此,在您的情况下,它将是
1 | image_json = request.files['here is the key you add to the file on postman'] |
其他被称为表单数据的内容将按请求提供.form。所以,要得到:
1 | form_data = request.form |
号
所以,使用postman,当您选择multipartm/form数据时,您将首先为该文件指定一个名称,然后选择它。名称(或键)将是dict中用于获取文件的键,如上所述。另外,对于窗体部分,键的工作方式相同