2010-06-22 3 views
0

내 서버에 .doc 및 .txt 문서를 업로드하고 있는데 다음 두 가지 옵션이 필요합니다. - 사용자가 문서를 다운로드 할 수 있습니다. - 사용자가 온라인으로 읽을 수 있습니다. 다운로드 기능에 대한 코드를 읽었지만 제대로 작동하지 않습니다.django가 서버에서 사용자 컴퓨터로 파일을 다운로드하거나 온라인으로 읽습니다.

내 코드 :

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() 

어떤 단서? 덕분에 !

+1

'file_name somewhere!'를 정의해야합니다. 'Courses' 모델에 저장되어 있습니까? (나는 그것이 코스가되는 것을 의미한다고 생각한다.). –

답변

4

[ 'X-Sendfile'] 응답이 파일을 가리키고 있습니까? 그것은 단지 '/ root /'를 가리키고있는 것처럼 보이는데, 나는 그것이 단지 디렉토리라고 추측합니다. 아마 보일 것 같은 더 : 당신은 다음 실제 파일을 읽기 위해 파일 개체를 열 수 있습니다

+0

'예기치 않은 인수 mimetype이 있습니다' – fanny

11

: get_path_to_course_download이 (/path/to/where/handle_uploaded_files/saves/files/the_file.doc 예) 파일 시스템에 다운로드의 위치를 ​​반환

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 

이 코드와 같은 파일을 다운로드 시작합니다

 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가 : 파일이 서버에있는 곳입니다. f = open(path_to_file, 'r') .. 파일을 읽는 중

나머지는 파일을 다운로드하는 것입니다.

+4

클래스는'django.core.files 파일 가져 오기 '입니다. –

관련 문제