dan*_*ana 1 forms django download
我在我的服务器上上传了一些.doc和.txt文件,我想有两个选择: - 用户能够下载文件 - 用户能够在线阅读我已经阅读了一些代码对于下载功能,但它似乎不起作用.
我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
任何线索?谢谢!
Moh*_*thy 12
您可以打开File对象来读取实际文件,然后像这段代码一样开始下载文件:
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
Run Code Online (Sandbox Code Playgroud)
path_to_file:是文件在服务器上的位置.
f = open(path_to_file, 'r')..阅读文件
剩下的就是下载文件.
| 归档时间: |
|
| 查看次数: |
12019 次 |
| 最近记录: |