我尝试使用DRF和jQuery构建文件上传。我用Google搜索并找到了this sample。我在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')
并尝试将Angular示例转换为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(...
由于某些原因,我在尝试上传文件时后端出错:
detail: "FileUpload parse error - none of upload handlers can handle the stream"
答案 0 :(得分:6)
实际上问题是一种解析器。我应该使用(FormParser, MultiPartParser, )
代替(FileUploadParser, )
答案 1 :(得分:3)
默认的Django上传处理程序是:
["django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler"]
默认情况下,应用设置文件中没有FILE_UPLOAD_HANDLERS参数。
在我的情况下,我已经排除了MemoryFileUploadHandler并设置了
FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.TemporaryFileUploadHandler", ]
在应用设置文件中,它解决了问题。