利用django实现文件下载

本文介绍了使用Django开发中如何通过视图定义下载功能,详细讲解了`download_file`视图如何获取文件对象并生成下载URL。模型`MyFile`展示了文件存储与管理。重点在于HTTP响应头设置和文件下载的实现。
摘要由CSDN通过智能技术生成

0.url

    path('download_file/', views.download_file, name='download_file'),

1. view

def download_file(request):
    """
    下载
    """
    id = request.GET.get('id')

    file_obj = models.MyFile.objects.filter(id=id).first()
    # http://127.0.0.1:8000/media/book/book.txt
    # http://127.0.0.1:8000/media/book/book.jpg  # 现在:book/book.txt
    url = 'http://127.0.0.1:8000' + file_obj.my_file.url
    # url = 'https://t33-1305448189.cos.ap-nanjing.myqcloud.com/p333.jpg'
    print(url)
    # 大文件的下载
    # data = requests.get(url).iter_content()
    # 正常文件的下载
    data = requests.get(url).content
    # 弹框提示框
    response = HttpResponse(data, content_type="application/octet-stream")
    # 中文转义
    from django.utils.encoding import escape_uri_path
    # 设置下载头
    # print(file_obj.my_file.url)
    name = file_obj.my_file.url.split('/')[-1]
    # print(name)
    response['Content-Disposition'] = "attachment;filename={};".format(escape_uri_path(name))
    return response

2.models.py

class MyFile(models.Model):
    """
    文件下载
    """
    name = models.CharField(verbose_name='名称', max_length=225)
    my_file = models.FileField(upload_to="my_file", verbose_name="教程", default='my_file/my_file.txt')

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Vue是一种流行的JavaScript框架,用于构建用户界面。Django是一个用于构建Web应用程序的Python框架。使用这两种框架可以很容易地实现文件下载的功能。 首先,在Django中,你需要创建一个视图函数来处理文件下载的请求。你可以使用Python的内置模块`open`来打开文件,并将其内容发送给浏览器。具体代码如下: ```python from django.http import FileResponse import os def download_file(request): file_path = '/path/to/your/file.pdf' # 文件路径 file_name = os.path.basename(file_path) # 获取文件名 response = FileResponse(open(file_path, 'rb'), as_attachment=True) response['Content-Disposition'] = f'attachment; filename="{file_name}"' return response ``` 在Vue中,你可以创建一个按钮或链接来触发文件下载的请求。使用`axios`库来发起HTTP请求并下载文件。具体代码如下: ```javascript <template> <div> <button @click="downloadFile">下载文件</button> </div> </template> <script> import axios from 'axios'; export default { methods: { downloadFile() { axios({ url: 'http://your-api-url/download', method: 'GET', responseType: 'blob', // 必须设置为blob }).then(response => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'file.pdf'); // 设置下载文件文件名 document.body.appendChild(link); link.click(); }); } } } </script> ``` 以上是一个简单的示例,演示了如何在Vue和Django实现文件下载的功能。当用户点击“下载文件”按钮时,Vue将发送一个HTTP请求到Django后端后端会返回文件的内容,然后前端利用Blob对象创建一个URL,最终通过创建一个a标签实现文件下载
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑猪去兜风z1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值