python-3.x - 如何使用 Sanic 提供上传的图片?
问题描述
我已经使用 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
如何提供上传的图片?
解决方案
我找到了阅读Sanic 静态文件的解决方案。我已使用蓝图选项将我上传的图像提供为:
static_file_bp = Blueprint('static', url_prefix='/files')
static_file_bp.static('/static', './uploads')
推荐阅读
- php - Laravel RESTfull Api:不允许 PUT 方法
- ssas - 有没有办法在 MDX 中动态累积测量?
- javascript - JS - 中心屏幕上的 Div
- python - 熊猫:从如何将嵌套的 JSON 解压缩为数据框?
- ffmpeg - 使用 frameskip 从视频 FFMPEG 中提取帧并相应地命名。\
- ruby-on-rails - 如何对关联错误消息进行分组?
- php - 按值对 Laravel 集合进行排序
- javascript - 为什么我的 fetch 在第一次调用时返回错误,但在后续调用中却没有?
- python - 使用基准年计算指数
- javascript - 我应该使用什么下拉菜单里面有很多元素?