diff --git a/binder/models.py b/binder/models.py index 717b4866..a489ddfd 100644 --- a/binder/models.py +++ b/binder/models.py @@ -825,12 +825,13 @@ class BinderFileField(FileField): attr_class = BinderFieldFile descriptor_class = BinderFileDescriptor - def __init__(self, allowed_extensions=None, *args, **kwargs): + def __init__(self, allowed_extensions=None, serve_direct=False, *args, **kwargs): # Since we also need to store a content type and a hash in the field # we up the default max_length from 100 to 200. Now we store also # the original file name, so lets make it 400 chars. kwargs.setdefault('max_length', 400) self.allowed_extensions = allowed_extensions + self.serve_direct = serve_direct return super().__init__(*args, **kwargs) def get_prep_value(self, value): @@ -903,11 +904,11 @@ class BinderImageField(BinderFileField): descriptor_class = BinderImageFileDescriptor description = _("Image") - def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, allowed_extensions=None, **kwargs): + def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, allowed_extensions=None, serve_direct=False, **kwargs): self.width_field, self.height_field = width_field, height_field if allowed_extensions is None: allowed_extensions = ['png', 'gif', 'jpg', 'jpeg'] - super().__init__(allowed_extensions, verbose_name, name, **kwargs) + super().__init__(allowed_extensions, serve_direct, verbose_name, name, **kwargs) def check(self, **kwargs): return [ diff --git a/binder/views.py b/binder/views.py index 4bec60f8..3a44cc06 100644 --- a/binder/views.py +++ b/binder/views.py @@ -2878,12 +2878,17 @@ def dispatch_file_field(self, request, pk=None, file_field=None): guess = mimetypes.guess_type(file_field.path) guess = guess[0] if guess and guess[0] else 'application/octet-stream' try: - resp = StreamingHttpResponse(open(file_field.path, 'rb'), content_type=guess) + if file_field.serve_direct: + resp = HttpResponse(content_type=guess) + else: + resp = StreamingHttpResponse(open(file_field.path, 'rb'), content_type=guess) except FileNotFoundError: logger.error('Expected file {} not found'.format(file_field.path)) raise BinderNotFound(file_field_name) if 'download' in request.GET: + if file_field.serve_direct: + resp['X-Accel-Redirect'] = '/internal/media/' + file_field.name filename = self.filefield_get_name(instance=obj, request=request, file_field=file_field) if 'prefix' in request.GET: filename = request.GET['prefix'] + ' - ' + filename