2

In my AngularJS/Python app, I uploaded a file using dropzone which has a physical path of something like this:

D:\uploadedFiles\tmpmj02zkex___5526310795850751687_n.jpg'

Now I want to create a link for this file for display and download on the front end. A link that looks something like this:

http://127.0.0.1:8000/uploadedFiles/tmpmj02zkex___5526310795850751687_n.jpg

What is the best way to achieve this?

Tahreem Iqbal
  • 985
  • 6
  • 17
  • 43

1 Answers1

0

You can simply add a url pattern in eg. urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    ...,
    url(r'^uploadedFiles/(?P<file_name>.+)/$', views.download, name='download')
]

and a download method in the controller in eg. views.py as suggested in here:

import os
from django.conf import settings
from django.http import HttpResponse

# path to the upload dir
UPLOAD_DIR = 'D:\uploadedFiles'

...

def download(request, file_name):
    file_path = os.path.join(UPLOAD_DIR, file_name)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/octet-stream")
            response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
            return response
    else:
        raise Http404
Community
  • 1
  • 1
Yohanes Gultom
  • 3,782
  • 2
  • 25
  • 38
  • do we need to specify the content type? the uploaded file can be of any type – Tahreem Iqbal Feb 13 '17 at 12:29
  • No, we don't, but it is recommended as explained in [here](http://stackoverflow.com/questions/20392345/is-content-type-http-header-always-required). I've updated the example so that it always force user to download regardless the file type – Yohanes Gultom Feb 13 '17 at 23:46
  • 1
    I had to change url pattern to `url(r'^uploadedFiles/(?P[\w\-.*]+)/$', download, name='download'),` and it worked. Thanks! – Tahreem Iqbal Feb 14 '17 at 10:12
  • Great. Ah my bad, you are right. It can be even simpler `(?P.+)` as suggested in [here](http://stackoverflow.com/questions/6164540/getting-two-strings-in-variable-from-url-in-django) – Yohanes Gultom Feb 14 '17 at 11:53