【问题标题】:How to serve uploaded image using Sanic?如何使用 Sanic 提供上传的图片?
【发布时间】:2019-09-05 16:30:13
【问题描述】:

我已经使用 Sanic 在我的项目的某个目录中成功上传了图像。我用来上传图片的代码如下:

class ImageUploadAPI(HTTPMethodView):
    async def post(self, request):
        access_token = get_token_from_header(request.headers)
        token = decode_token(access_token)
        user_id = token.get('sub')
        upload_file = request.files.get('image')
        log_path = os.path.join(os.getcwd(), 'pictures')
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        if not upload_file:
            res = {'status': 'no file uploaded'}
            return json(res, status=404)

    # if not valid_file_type(upload_file.name, upload_file.type):
    #     res = {'status': 'invalid file type'}
    #     return json(res, status=400)
        elif not valid_file_size(upload_file.body):
            res = {'status': 'invalid file size'}
            return json(res, status=400)
        else:
            file_path = f"{log_path}/{str(datetime.now())}.{upload_file.name.split('.')[1]}"
            await write_file(file_path, upload_file.body)
            await apps.db.users.update_one({'_id': ObjectId(user_id)}, {"$set": {
            "nid_front": upload_file.name
            }})
            return json({'status': 'image uploaded successfully'})

在此过程中,我将upload_file.name 保存在user 字段中。 现在为了提供上传的图片,我访问了以下网址(因为我在本地服务器中http://localhost:8000/10414532_479247615552487_2110029531698825823_n.jpg 但它不显示图像,而是显示,

Error: Requested URL /10414532_479247615552487_2110029531698825823_n.jpg not found

如何提供上传的图片?

【问题讨论】:

    标签: python-3.x sanic


    【解决方案1】:

    我找到了Sanic static files 的解决方案。 我已使用 blueprint 选项将我上传的图片作为:

    static_file_bp = Blueprint('static', url_prefix='/files')
    static_file_bp.static('/static', './uploads')
    

    【讨论】:

    • 考虑接受您自己的答案,以帮助有类似问题的其他用户。可见问题有一个可行的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多