当我尝试将FormData提交到DRF时,我收到此错误The submitted data was not a file. Check the encoding type on the form
。这是我的代码:
jquery的:
upload(e) {
e.preventDefault();
let data = new FormData();
data.append('name', ReactDOM.findDOMNode(this.refs.name).value);
data.append('album', ReactDOM.findDOMNode(this.refs.album).value);
data.append('playlist', 1);
data.append('file', ReactDOM.findDOMNode(this.refs.file).value);
$.ajax({
url: '/api/music/',
method: 'post',
headers: {
'Authorization': 'JWT ' + sessionStorage.getItem('token')
},
contentType: false,
data: data,
processData: false
}).done(function (res) {
console.log(res.responseText);
}).fail(function (error) {
console.error(error.responseText);
});
串行器:
class MusicSerializer(serializers.ModelSerializer):
file = serializers.FileField()
class Meta:
model = Music
fields = ('id', 'favorite', 'created_at', 'file', 'counter', 'name', 'album', 'playlist')
并查看:
class MusicViewSet(viewsets.ModelViewSet):
authentication_classes = (CsrfExemptSessionAuthentication, JSONWebTokenAuthentication)
queryset = Music.objects.all()
serializer_class = MusicSerializer
parser_classes = (FormParser, MultiPartParser)
def perform_create(self, serializer):
file_obj = self.request.FILES['file']
#dbx = dropbox.Dropbox(JSON_DATA['dropbox_access_token'])
#res = dbx.files_upload(file_obj, '/', autorename=True, mute=True)
print(file_obj)
#serializer.save(dropbox_id='x')
答案 0 :(得分:0)
终于找到了解决方案。我需要使用
data.append('file', ReactDOM.findDOMNode(this.refs.file).files[0]);