如果您尝试使用Axios将图像传递给Django后端但遇到问题,可以使用以下示例代码检查您的代码是否有问题:
前端代码示例:
import axios from 'axios';
const formData = new FormData();
formData.append('image', imageFile);
formData.append('name', 'test');
axios.post('<后端API地址>', formData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
后端代码示例:
from django.http import JsonResponse
def upload_image(request):
if request.method == 'POST':
image = request.FILES.get('image')
name = request.POST.get('name')
# do something with the image and name
return JsonResponse({'message': 'success'}, status=200)
return JsonResponse({'error': 'Invalid Request'}, status=400)
请确保您的Axios配置正确并且在FormData对象中正确添加了图像文件。在Django后端代码中,您需要使用FILES而不是POST来获取文件。此外,请在FormData对象中使用正确的键值来获取图像和其他数据,并通过JSONResponse返回相应的数据和状态码。