django 实现文件上传并保存

html超链接直接下载不再网页中打开,在a标签里添加 download=””,””里面的内容可随意写,比如文件名

<a href="/download/下载.pdf" download="">下载.pdfa>
from django.db import models

class UploadFile(models.Model):
    title = models.CharField(verbose_name="图片标题", max_length=50)
    path = models.FileField(upload_to='files/')
from django.shortcuts import render, HttpResponse
from .models import UploadFile

def upload_file(request):
    if request.method == "POST":
        up_file = request.FILES.get('upload_file')
        UploadFile(title=up_file.name, path=up_file).save()
        return HttpResponse('success')
    else:
        return render(request, "blog/upload_file.html")
  • enctype="multipart/form-data"
  • name="upload_file"request.FILES.get('upload_file') 名字对应
    <form action="{% url "upload_file" %}" role="form" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="form-group text-center">
            <label for="inputfile" class="col-md-2">上传文件</label>
            <div class="col-md-10">
                <input name="upload_file" type="file" id="inputfile">
            </div>
        </div>
        <div style="clear: both"></div>
        <p style="margin-top: 100px"><button type="submit" class="col-sm-offset-2 btn btn-primary">提交文件 </button></p>
    </form>
  • 指定上传文件保存路径的根目录
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
from django.urls import path
from . import views

urlpatterns = [
    path('uploadfile/', views.upload_file, name="upload_file"),

]

实现保存的文件与 request 内容相关

def upload_file(request):
    if request.method == "POST":
        up_file = request.FILES.get('upload_file')
        UploadFile(title=up_file.name, path=up_file).save(request=request)
        return HttpResponse('success')
    else:
        return render(request, "blog/upload_file.html")

函数默认会传入

  • instanceUploadFile 实例
  • filename 为文件名
from django.db import models

def upload_path(instance, filename):
    print(instance.rq)
    print(filename)
    return "files/"

class UploadFile(models.Model):
    title = models.CharField(verbose_name="图片标题", max_length=50)
    path = models.FileField(upload_to=upload_path)
    rq = None

    def save(self, *args, **kwargs):
        UploadFile.rq = kwargs.pop("request")
        print(UploadFile.rq)
        super().save(*args, **kwargs)
  • 对模型添加设置与获取 request 的方法
from django.shortcuts import render, HttpResponse
from .models import UploadFile

def upload_file(request):
    if request.method == "POST":
        up_file = request.FILES.get('upload_file')
        f = UploadFile(title=up_file.name, path=up_file)
        f.set_request(request)
        f.save()
        return HttpResponse('success')
    else:
        return render(request, "blog/upload_file.html")
from django.db import models

def upload_path(instance, filename):
    print(instance.get_request().method)
    print(filename)
    return "files/"

class UploadFile(models.Model):
    title = models.CharField(verbose_name="图片标题", max_length=50)
    path = models.FileField(upload_to=upload_path)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

    def set_request(self, request):
        self.request = request

    def get_request(self):
        return self.request
STATIC_URL = '/static/'
STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'static'),
   MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')

下载界面

    {% for file_obj in file_list %}
    <div class="row">
        <a href="/upload/{{ file_obj.path }}">{{ file_obj.title }}</a>
    </div>
    {% endfor %}
  • 保存到 media 目录,需要配置路由, path 会自动传入 serve 作为参数
from django.conf.urls import url
from django.urls import path
from django.views.static import serve

urlpatterns = [
    url(r'^media/(?P.*)', serve, {"document_root": settings.MEDIA_ROOT}),
]
  • 保存到 media 目录
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'static'),
   os.path.join(BASE_DIR, 'upload')
]

urls.py

from django.urls import path
from . import views

urlpatterns = [

    path('uploadfile/', views.upload_file, name="upload_file"),

]

views.py

def upload_file(request):
    if request.method == "POST":
        up_file = request.FILES.get('upload_file')
        UploadFile(title=up_file.name, path=up_file).save(request=request)
        return HttpResponse('success')
    else:
        return render(request, "blog/upload_file.html")

models.py

class UploadFile(models.Model):
    title = models.CharField(verbose_name="图片标题", max_length=50)
    path = models.FileField(upload_to='attach_file/')

upload_file.html

    <form action="{% url "upload_file" %}" role="form" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="form-group text-center">
            <label for="inputfile" class="col-md-2">上传文件</label>
            <div class="col-md-10">
                <input name="upload_file" type="file" id="inputfile">
            </div>
        </div>
        <div style="clear: both"></div>
        <p style="margin-top: 100px"><button type="submit" class="col-sm-offset-2 btn btn-primary">提交文件 </button></p>
    </form>

下载,直接在静态文件目录下查找对应文件,需要加入 STATICFILES_DIRS

<a style="color: #fff;" href="/static/{{ attach.file }}" download="{{ attach.title }}">下载</a>

Original: https://blog.csdn.net/sky0Lan/article/details/120550016
Author: sky0Lan
Title: django 实现文件上传并保存

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/735056/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Oracle 序列学习与使用总结

    by:授客 QQ:1033553122 序列是oracle提供的用于生成一系列数字的数据库对象,序列会自动生成顺序递增的序列号,可用于提供唯一的自动递增主键。序列和视图一样,并不占…

    Python 2023年6月6日
    050
  • 机器学习-感知机模型

    一、引言 单层感知机是神经网络的一个基本单元,类似于人类的神经网络的一个神经元,神经网络是由具有适应性的简单单元(感知机)组成的广泛并行互连的网络,它的组织能够模拟生物神经系统对真…

    Python 2023年10月28日
    046
  • GPS定位原理

    GPS卫星: 卫星定位系统是一种使用卫星对某物进行准确定位的技术,它从最初的定位精度低、不能实时定位、难以提供及时的导航服务,发展到现如今的高精度GPS全球定位系统,实现了在任意时…

    Python 2023年10月27日
    045
  • 一、搭建django自动化平台(实现一键执行sql)

    项目地址: GitHub – 18713341733/djangoplatform 背景: 测试的时候,有一个清理数据的场景,需要将一些信息从不同的几个库里的表删掉。 …

    Python 2023年8月5日
    054
  • [深度学习] fast-reid入门教程

    fast-reid入门教程 ReID,全拼为Re-identification,目的是利用各种智能算法在图像数据库中找到与要搜索的目标相似的对象。ReID是图像检索的一个子任务,本…

    Python 2023年9月7日
    0244
  • 手写字体识别实验-Python课程设计

    安装python打开手写识别文件夹中的安装包文件夹,双击python3.7.1可执行文件,进行安装。 弹出窗口第一步,勾选第二个复选框 Add Python 3.7 to PATH…

    Python 2023年9月1日
    046
  • 用Python写了一个上课点名系统(附源码)(自制考勤系统)

    今天浏览了这样的短视频后,我想我是否可以写一个类似的点名程序。我等不下去了。只要说和写就行了。 [En] After browsing a short video like thi…

    Python 2023年5月24日
    073
  • Django学习记录14

    关系映射 数据库中的关系映射,可以有一对一、一对多、多对多。 一、一对一 当两张表出现一对一关系时,在任何一个模型类内部定义一个外键。 创建一对一映射: class A(model…

    Python 2023年8月4日
    051
  • pytest之fixture使用详解

    pytest之fixture使用详解 usefixtures与传fixture区别 1、如果fixture有返回值,那么usefixture就无法获取到返回值,这个是装饰器usef…

    Python 2023年9月12日
    047
  • python学习:map函数和filter函数用法教程

    map()函数可以对一个数据进行同等迭代操作。 例如: def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])…

    Python 2023年10月31日
    031
  • 带你从0到1开发AI图像分类应用

    摘要:通过一个垃圾分类应用的开发示例,介绍AI Gallery在AI应用开发流程中的作用。 现如今,人工智能(AI)技术在计算机领域内,得到了越来越广泛的重视,并在各行各业中得到应…

    Python 2023年10月28日
    049
  • 听说你想面对监狱编程,你,够格吗?

    先说明一下,我的这篇文章没有太多的技术含量,最多只有一些的技术总结,剩下的是我这几个月算是自身经历吧,但是没跑题啊,还是跟爬虫技术的先关的,不喜欢可以关了哈,来都来了就看看呗,没准…

    Python 2023年8月1日
    065
  • Django之 Timezone 详解

    最近在做项目时发现存储的时间比本地时间慢了八小时,查了很多文章,感觉都没有讲的很明白,本文根据自己的理解和如何解决的详细的记录下来,但也参考了一些文章和官网介绍。 datetime…

    Python 2023年8月5日
    045
  • Python Web框架

    本篇文章主要介绍Redis的基本知识 五种数据结构(增删改查命令)+Python如何连接Redis PythonWeb框架 Web应用程序处理流程:前端客服端(浏览器、App、aj…

    Python 2023年8月13日
    040
  • 逢年过节就拿出这些代码,Python 制作一个炫酷烟花秀

    Original: https://www.cnblogs.com/sn520/p/15759337.htmlAuthor: Python可乐呀Title: 逢年过节就拿出这些代码…

    Python 2023年5月24日
    064
  • Python 创建一个空的DataFrame,并按行写入数据

    方法1 import pandas as pd df = pd.DataFrame(columns = [‘A’,’B’,’C’,’D’]) for i in range(4): …

    Python 2023年8月19日
    040
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球