我正在尝试使用 vue 组件和 django Rest 框架上传图像。这是 html 的片段
<div class="mb-3 mx-5">
<label for="image" class="form-label">Upload an image that best describes the survey</label>
<input class="form-control" type="file" ref="file" name="image" id="image" @change="onFileSelected()">
</div>
这是我用来将数据发送到后端的 vue 方法
methods: {
onFileSelected() {
this.image = this.$refs.file.files.item(0)
},
sendData (file) {
const formData = new FormData()
formData.append('image', file)
axios.post('/api/v1/surveys/', this.SurveyList, formData, {
headers: {
"Content-Type": "multipart/form-data",
"X-CSRFToken": "{{ csrf_token }}"
}
})
.then(response => {
this.SurveyList = response.data
})
.catch(error => {
console.log(error)
})
}
}
我收到以下错误
The submitted data was not a file
,然后尝试实现此处讨论的更改 Django REST Framework 上传图像:“提交的数据不是文件” 但现在我收到此错误 This field may not be null.
这是我的序列化器.py
class SurveySerializer(serializers.ModelSerializer):
image = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = Survey
fields = (
"id",
"category",
"description",
"location",
"image",
"question1",
"questiontype1",
"choice1a",
"choice2a",
"choice3a",
"choice4a",
)
这是我的观点.py
def post(self, request, format=None):
serializer = SurveySerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
可能是什么问题?
你解决这个问题了吗?我这几天也遇到同样的问题