0

I am getting error while storing the file into folder using Django and Python. I am providing the error below.

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/lampp/htdocs/rework/Nuclear/RFI15/vlnerable/plant/views.py", line 267, in downloadfile
    fyl.write(response)
TypeError: expected a character buffer object
[12/Sep/2017 10:52:35] "POST /downloadfile/ HTTP/1.1" 500 71558
Performing system checks...

I am providing my code below.

def downloadfile(request):
    """ This function helps to download the file from remote site"""

    if request.method == 'POST':
        URL = request.POST.get('file')
        filename = "status.txt"
        response = HttpResponse(content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename='+filename
        with open(settings.FILE_PATH + filename, 'w') as fyl:
            fyl.write(urllib2.urlopen(URL).read())
            fyl.write(response)
        return response

I am getting that error in this fyl.write(response) line. Here I am including the remote file and download it. After downloading its storing inside the folder.

halfer
  • 19,824
  • 17
  • 99
  • 186
satya
  • 3,508
  • 11
  • 50
  • 130

2 Answers2

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

def download(request, path):
    if request.method == 'POST':
       URL = request.POST.get('file')
       path_with_filenmae = "status.txt" #you can define file name with path
       file_path = os.path.join(settings.MEDIA_ROOT, path_with_filenmae)
       if os.path.exists(file_path):
           with open(file_path, 'rb') as fh:
           response = HttpResponse(fh.read(), content_type="text/plain")
           response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
           return response
       raise Http404
Robert
  • 3,373
  • 1
  • 18
  • 34
0

There is a detailed example about file upload with Django on SO: Need a minimal Django file upload example

To summerise:

if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        newdoc = Document(docfile = request.FILES['docfile'])
        newdoc.save()

And a blog post here: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103