1

I am uploading some .doc and .txt documents on my server, and i'd like to have two options: -the user to be able to download the document -the user to be able to read it online i've read some code for the download function, but it doesn't seem to work.

my code:

def download_course(request, id):
    course = Courses.objects.get(pk = id)
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
    response['X-Sendfile'] = smart_str(/root/)
    return response

def save_course(request, classname):
   classroom = Classroom.objects.get(classname = classname)
   if request.method == 'POST':
        form = CoursesForm(request.POST, request.FILES)
        if form.is_valid():
           handle_uploaded_file(request.FILES['course'])
           new_obj = form.save(commit=False)
           new_obj.creator = request.user
           new_obj.classroom = classroom
           new_obj.save()
           return HttpResponseRedirect('.')    
   else:
           form = CoursesForm()     
   return render_to_response('courses/new_course.html', {
           'form': form,
           }, 
          context_instance=RequestContext(request)) 


def handle_uploaded_file(f):
    destination = open('root', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)

    destination.close()

any clue? thanks!

dana
  • 5,168
  • 20
  • 75
  • 116

2 Answers2

12

You can open a File object to read the actual file, and then start download the file like this code:

        path_to_file = os.path.realpath("random.xls")
        f = open(path_to_file, 'r')
        myfile = File(f)
        response = HttpResponse(myfile, content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=' + name
        return response

path_to_file: is where the file is located on the server. f = open(path_to_file, 'r') .. to read the file

the rest is to download the file.

tkanzakic
  • 5,499
  • 16
  • 34
  • 41
Mohammed Fathy
  • 357
  • 2
  • 10
4

Should the response['X-Sendfile'] be pointing to the file? It looks like it's only pointing at '/root/', which I'm guessing is just a directory. Maybe it should look more like this:

def download_course(request, id):
    course = Courses.objects.get(pk = id)
    path_to_file = get_path_to_course_download(course)

    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
    response['X-Sendfile'] = smart_str(path_to_file)
    return response

Where get_path_to_course_download returns the location of the download in the file system (ex: /path/to/where/handle_uploaded_files/saves/files/the_file.doc)

Eric Palakovich Carr
  • 22,701
  • 8
  • 49
  • 54