django2上传文件
作者:互联网
一、简易版的上传文件
-
1、前端代码
<form action="/file/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <input type="submit" value="提交"> </form>
-
2、后端代码
from django.shortcuts import render from django.http import HttpResponse from django.views import View class UploadFileView(View): """ 上传文件 """ def get(self, request, *args, **kwargs): return render(request, 'upload_file.html') def post(self, request, *args, **kwargs): my_file = request.FILES.get('file') with open(my_file.name, 'wb') as fp: for chunk in my_file.chunks(): fp.write(chunk) return HttpResponse('上传成功')
二、结合数据模型来上传文件
上面的方式仅仅是把文件上传到本项目文件夹下,如果要存储到数据库,就要使用数据模型
-
1、创建数据模型
from django.db import models class UploadFileModel(models.Model): """ 上传文件的数据模型 """ title = models.CharField(max_length=100, verbose_name='标题') # upload_to指定上传的路径 file = models.FileField(upload_to='files') class Meta(object): db_table = 'c_file'
-
2、在视图类中使用
class UploadFileView(View): """ 上传文件 """ def get(self, request, *args, **kwargs): return render(request, 'upload_file.html') def post(self, request, *args, **kwargs): title = request.POST.get('title') file = request.FILES.get('file') models.UploadFileModel.objects.create(title=title, file=file) return HttpResponse('上传成功')
-
3、最终在数据库存储的
三、配置静态文件
前面既然已经上传成功了,那么前端要显示,就需要配置静态文件路径
-
1、在
settings.py
中配置媒体的根目录及根路由MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
-
2、配置静态文件路径(项目的根路由中)
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('home.urls', namespace='home')), ... path('file/', include('upload_file.urls', namespace='upload_file')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
-
3、在浏览器中输入
http://localhost:8000/media/files/22.JPEG
四、其它补充
-
1、限制文件上传类型
class UploadFileModel(models.Model): """ 上传文件的数据模型 """ title = models.CharField(max_length=100, verbose_name='标题') file = models.FileField(upload_to='files', validators=[validators.FileExtensionValidator(['gif', 'png', 'jpeg'], message='上传图片格式错误')]) class Meta(object): db_table = 'c_file'
-
2、修改上传文件路径(根据年/月/日来显示)
... file = models.FileField(upload_to='%Y/%m/%d', validators=[... ...
-
3、如果是仅仅是上传图片的话,可以使用下面的
class UploadFileModel(models.Model): """ 上传文件的数据模型 """ title = models.CharField(max_length=100, verbose_name='标题') # 需要先安装pillow file = models.ImageField(upload_to='%Y/%m/%d') class Meta(object): db_table = 'c_file'
五、对上传文件重命名
-
1、定义一个通用的方法
import os import time import random from django.core.files.storage import FileSystemStorage from django.conf import settings class FileStorage(FileSystemStorage): def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL): super().__init__(location, base_url) def _save(self, name, content): ext = os.path.splitext(name)[1] dir = os.path.dirname(name) fn = time.strftime('%Y%m%d%H%M%S') fn = '{}_{}'.format(fn, random.randint(0, 100)) name = os.path.join(dir, '{}{}'.format(fn, ext)) return super()._save(name, content)
-
2、使用
class UploadFileModel(models.Model): """ 上传文件的数据模型 """ title = models.CharField(max_length=100, verbose_name='标题') file = models.FileField(upload_to='%Y/%m/%d', storage=FileStorage()) class Meta(object): db_table = 'c_file'
标签:文件,name,models,django2,file,import,上传,class 来源: https://blog.csdn.net/kuangshp128/article/details/89423100