Django Rest框架和文件上传 [英] Django Rest Framework and File Upload
本文介绍了Django Rest框架和文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类附件(BaseModel):
file = models.FileField(upload_to = get_photo_path)
class AttachmentSerializer(serializers.ModelSerializer):
class Meta:
model = models.Attachment
fields =('id','文件')
class AttachmentViewSet(viewsets.ModelViewSet):
parser_classes =(FileUploadParser,)
serializer_class = serializers.AttachmentSerializer
queryset = models.Attachment.objects。全部()
def pre_save(self,obj):
obj.file = self.request.FILES.get('file')
并尝试将Angular样本转换为jQuery
var fd = new FormData()
fd.append('file',file)//文件从文件字段
var reader = new FileReader()
$ .ajax({
url:'http:// localhost:8001 / files /',
data:fd,
processData:false ,
contentType:false,
type:'POST'
})。done(...
由于某些原因,当尝试上传文件时,我有一个后端错误:
detail :FileUpload解析错误 - 没有一个上传处理程序可以处理流
解决方案
其实问题是一种解析器。我应该使用(FormParser,MultiPartParser,)
而不是(FileUploadParser,)
I'm trying to build file upload with DRF and jQuery. I googled and found this sample. I have some similar code on beckand:
class Attachment(BaseModel):
file = models.FileField(upload_to=get_photo_path)
class AttachmentSerializer(serializers.ModelSerializer):
class Meta:
model = models.Attachment
fields = ('id', 'file')
class AttachmentViewSet(viewsets.ModelViewSet):
parser_classes = (FileUploadParser, )
serializer_class = serializers.AttachmentSerializer
queryset = models.Attachment.objects.all()
def pre_save(self, obj):
obj.file = self.request.FILES.get('file')
And tried to translate Angular sample to jQuery
var fd = new FormData()
fd.append('file', file) // file from file-field
var reader = new FileReader()
$.ajax({
url: 'http://localhost:8001/files/',
data: fd,
processData: false,
contentType: false,
type: 'POST'
}).done(...
For some reasons I have an error on backend when try to upload a file:
detail: "FileUpload parse error - none of upload handlers can handle the stream"
解决方案
Actually the problem is a type of parser. I should use (FormParser, MultiPartParser, )
instead of (FileUploadParser, )
这篇关于Django Rest框架和文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文