我正在尝试仅使用/ Django rest框架和REACT / Axios上传文件(以及文件名),但我不明白我在做什么错。
我有此错误:
request.response:“ {” my_file“:[”未提交文件。“]}”
这是我的 REACT前端:
uploadFile = e => {
e.preventDefault();
let formData = new FormData();
formData.append('my_file', e.target.files[0]);
axios.post('http://127.0.0.1:8000/uploadFiles/', {
formData,
name: 'name',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'multipart/form-data'
},
})
.then(() => {
console.log('All Done',);
})
.catch(error => {
console.log('error.response: ', error.response);
});
}
render() {
return (
<input
type='file'
onChange={this.uploadFile}
/>
);
}
这是我的Django REST后端,具有:
models.py:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class File(models.Model):
my_file = models.FileField(upload_to=user_directory_path)
name = models.CharField(null=False, max_length=50)
upload_date = models.DateTimeField(auto_now_add=True)
serializers.py
FileSerializer类(serializers.ModelSerializer):
class Meta:
model = File
fields = (
'id',
'my_file',
'name',
'upload_date',
)
views.py
class UploadFileView(views.APIView):
parser_classes = (JSONParser, MultiPartParser, FormParser,)
def post(self, request, *args, **kwargs):
fileSerializer = FileSerializer(data=request.data)
if fileSerializer.is_valid():
fileSerializer.save()
return Response(fileSerializer.data, status=status.HTTP_201_CREATED)
else:
return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST)
我在编写此代码时遇到很多困难,我想快要结束了,但我不知道为什么不提交此文件。
答案 0 :(得分:0)
以下是使上传工作正常进行的修改:
uploadFile = e => {
let formData = new FormData();
formData.append('my_file', e.target.files[0]);
formData.append('name', 'var name here');
const url = 'http://127.0.0.1:8000/uploadFiles/';
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
axios.post(url, formData, config)
.then(() => {
console.log('All Done',);
})
.catch(error => {
console.log('error: ', error);
console.log('error.response: ', error.response);
});
}