我为s3设置了功能,我可以轻松地从Django管理界面上传图片。我有 "createProduct "页面,我想通过从next.js发送表单数据来创建一个产品。Django在数据库中存储URL s3 bucket,并在需要时从s3检索图片。
我设置了查看图片和裁剪的功能,它也能正常工作。为此我有一个单独的组件。
<div className="form-group">
<label htmlFor="image">Image</label>
<FileLoader
onFileUpload={image => setValue('image', image._id)}
我需要创建一个端点。管理员,首先上传图片,图片被保存到s3,然后管理员得到图片的URL,并把它传递给表单数据,所以表单数据将被发送到createProduct端点。
@api_view(['POST'])
@permission_classes([IsAdminUser])
def createProduct(request):
user=request.user
print("user in post",user)
print("request.data",request.data)
name=request.data['name']
price=request.data['price']
brand=request.data['brand']
countInStock=request.data['countInStock']
category=request.data['category']
description=request.data['description']
// Here i need to send the imag url I guess
image=request.FILES.get('image')
print("image",image)
product=Product.objects.create(user=user, name=name,
price=price,brand=brand,
countInStock=countInStock,category=category,description=description, image=image)
product.save()
serializer=ProductSerializer(product, many=False)
return Response(serializer.data)
这就是s3上传的端点。
@api_view(['POST'])
def upload(request):
data=request.data
print("image data sent",data)
client=boto3.client("s3",
aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'),
aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY'),
# s3 does not need region
# region_name=os.environ.get(AWS_REGION_NAME),
response = client.upload_fileobj(data,"bingology-bucket","testing",{'ContentType': "image/jpeg"}
我得到了成功上传的消息,图片在桶中,但它确实只显示黑色背景,"类型 "是"-"。
我还尝试获取预签名的url,我得到了url,但它没有保存任何东西到s3。