5

Is there any way to stream file from remote URL with Django Response (without downloading the file locally)?

# view.py
def file_recover(request, *args, **kwargs):    
    file_url = "http://remote-file-storage.com/file/111"

    return StreamFileFromURLResponse(file_url)

We have file storage (files can be large - 1 GB and more). We can't share download url (there are security issues). File streaming can significantly increase download speed by forwarding download stream to Django response.

Alex T
  • 4,331
  • 3
  • 29
  • 47
  • 1
    Does [this question](http://stackoverflow.com/questions/18814162/serving-a-downloadable-file-huge-from-remote-with-django) help you at all? – Tony May 13 '17 at 09:36
  • Yeah, that's it. I was looking for snippets how to implement it. – Alex T May 13 '17 at 12:05

1 Answers1

17

Django has built in StreamingHttpResponse class which should be given an iterator that yields strings as content. In example below I'm using requests Raw Response Content

import requests
from django.http import StreamingHttpResponse


def strem_file(request, *args, **kwargs):
    r = requests.get("http://host.com/file.txt", stream=True)

    resp = StreamingHttpResponse(streaming_content=r.raw)

    # In case you want to force file download in a browser 
    # resp['Content-Disposition'] = 'attachment; filename="saving-file-name.txt"'

    return resp

Alex T
  • 4,331
  • 3
  • 29
  • 47
  • I found this the only solution in case of serving private S3 image that requires retrieving temporary presigned url. What I don't understand is there's just so little information about this approach online, so I really wonder why this is not mentioned anywhere else when it comes to displaying private s3 image from a frontend webpage (e.g. ``. – Shawn Dec 19 '21 at 11:09