【发布时间】:2015-08-11 18:42:24
【问题描述】:
我发现很多类似的问题,但没有很好的答案。我有一个仪表板,用户可以在其中上传文件并显示他们上传的文件。我希望他们能够单击图标或文件名并下载。现在它会在浏览器中打开文件,这对于图像和 pdf 来说不是问题,因为您可以从那里保存。但是当你有一个 docx 或二进制文件或 zip 文件时,你需要一个下载链接,即使是 pdf 和图像也可以。
这是我的观点,忽略注释掉的部分:
@login_required(login_url='/dashboard-login/')
def dashboard(request):
current_user = request.user
current_client = request.user.client
files = ClientUpload.objects.filter(client=current_client)
if request.method == 'POST':
if request.FILES is None:
return HttpResponseBadRequest('No Files Attached.')
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
#dz_files = request.FILES
#for f in dz_files:
# new_file = ClientUpload(client=current_client, file_upload=f)
# new_file.save()
# logger = logging.getLogger(__name__)
# logger.info("File uploaded from " + current_client.company)
newfile = ClientUpload(client=current_client, file_upload=request.FILES.get('file_upload'))
newfile.save()
logger = logging.getLogger(__name__)
logger.info("File uploaded from " + current_client.company)
else:
logger = logging.getLogger(__name__)
logger.warning("Upload Failed")
return HttpResponseRedirect(reverse('dashboard'))
else:
form = UploadFileForm()
data = {'form': form, 'client': current_client, 'files': files}
return render_to_response('dashboard.html', data, context_instance=RequestContext(request))
这里是模板,不用担心过滤器,它只是基本名称,充当文件名的 os.path.basename。它不适用于任何问题:
{% load i18n %}
{% load staticfiles %}
{% load sasite_filters %}
<table class="table">
<tr>
<th>{% blocktrans %}Filename{% endblocktrans %}</th>
<th>{% blocktrans %}Size (Bytes){% endblocktrans %}</th>
<th>{% blocktrans %}Upload Time{% endblocktrans %}</th>
<th>{% blocktrans %}Actions{% endblocktrans %}</th>
</tr>
{% for file in files %}
{% with uploaded_file=file.file_upload %}
<tr>
<th><a href="{{ MEDIA_URL }}{{ file.relative_path }}">{{ uploaded_file.name|basename }}</a></th>
<th>{{ uploaded_file.size }}</th>
<th>{{ file.created_at }}</th>
<th><a href="{{ uploaded_file.url }}" id="view-btn"><i class="fa fa-search"></i></a><a href="{% url 'dashboard-delete' upload_id=file.id %}"><i class="fa fa-trash-o"></i></a></th>
{% endwith %}
{% endfor %}
</tr>
</table>
如您所见,我有两个图标,一个删除图标和一个查看图标。我想制作一个下载图标,或将文件名设为下载链接。但是当我执行<a href="{{ MEDIA_URL }}{{ file.relative_path }}">Download</a> 之类的操作时,它只会在浏览器中打开。
relative_path 只是模型上的一个属性,我也可以在没有 MEDIA_URL 的情况下使用 file_upload.path,但它是一回事。
我也试过把file:///放在网址前面,它什么也没做,甚至在浏览器中都打不开。
我读到我可以这样做:
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.filename
response.write(p.body)
来自Django Serving a Download File
但这是在视图中,我需要以某种方式在模板内部执行此操作,或者找到一种在视图中执行此操作的方法,但我不知道如何执行此操作。我考虑过使用process_response 的中间件,但我不知道在这种情况下如何编写它。
我需要通过视图的行:files = ClientUpload.objects.filter(client=current_client) 获取为该用户显示的所有文件,并找到一种方法将它们作为下载提供,而不是在浏览器中打开 URL。
如果有人对这种情况有任何经验,或者知道如何自定义我的模板、视图或添加其他东西来处理这个问题,那么举一个小例子会很有帮助。
我已经坚持了很长一段时间,似乎无法让它发挥作用。任何建议将不胜感激。
【问题讨论】: