我是一名后端开发人员,主要工作于Django-Rest-框架。我在 axios 后调用中发送图像时遇到一些问题。前端在这里发送这样的对象
{
"merchant": 2,
"category": [
7
],
"brand":7
, "name":"picture55test",
"best_seller":true,
"top_rated":false,
"collection":10,
"description":"abc",
"featured": false,
"availability": "in_stock",
"warranty": "no_warranty",
"rating":5,
"image":null,
"services": "cash_on_delivery",
"variants": [
{
"product_id": "OAXWRTZ_12C",
"price": "500.00",
"size": "not applicable",
"color": "not applicable",
"variant_image": null,
"quantity": 10,
"variant_availability": "available"
},
{
"product_id": "OGROUPIRZ_12C",
"price": "888.00",
"size": "not applicable",
"color": "not applicable",
"variant_image": null,
"quantity": 10,
"variant_availability": "available"
}
]
}
现在我知道的是,当我们必须向 formdata 附加一个字段时,我们必须这样做:
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state);
let form_data = new FormData();
form_data.append('image', this.state.image, this.state.image.name);
form_data.append('name', this.state.name);
form_data.append('services', this.state.services);
let url = 'http://localhost:8000/api/addproducts';
axios.post(url, form_data, {
headers: {
'content-type': 'multipart/form-data'
}
现在,正如您所看到的,我有一组正在发送的变体数据。如何在变体数组中附加字段,就像我在上面的代码片段中附加产品名称一样?
在后端,我使用了 JsonParser 和 Formparser,因为正在发送图像文件。我不知道这是否有帮助,但我如下所示:
class ProductAddAPIView(CreateAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser,JSONParser,FormParser]
queryset = Product.objects.all()
serializer_class = AddProductSerializer
我已将用于同时创建产品对象和变体对象的逻辑放入序列化器中,但我想这里没有必要。我只需要知道如何传递数组内的图像文件,例如上面数据中的变量数组。