从next.js上传的图片到django存储在aws s3中是空白的。

1 人关注

我为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。

3 个评论
你遇到的具体问题是什么?
@juliomalves 我可以写终端。所有的教程或文章都显示了如何设置s3的设置和从django管理员上传。
@juliomalves 我忘了编辑问题以添加端点
django
amazon-s3
django-rest-framework
next.js
boto3
Yilmaz
Yilmaz
发布于 2021-10-13
1 个回答
Igor Eulálio
Igor Eulálio
发布于 2021-10-13
0 人赞同

我认为我们需要另一个端点,用这个架构来处理上传的逻辑。

  • uploadImage(另一个端点的名称)从next js接收图像元数据。
  • uploadImage生成一个预先签名的URL(因为你使用的是S3),将这个URL返回给nextjs,nextjs使用这个预先签名的URL进行上传,并调用createProduct端点,将URL(uploadImage可以过滤以返回对象的确切URL)和所有产品数据存储在数据库中。
  • 这种方法可以更好地使用SAGA模式来协调事情,因为你需要处理两个不同的过程(s3上传和数据库事务),你可以协调这些事情,或者在一个单一的架构中使用事务(所有业务逻辑在一个部署中)。