一、前端代碼html
<form action="/file/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<input type="submit" value="提交">
</form>
複製代碼
二、後端代碼前端
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('上傳成功')
複製代碼
上面的方式僅僅是把文件上傳到本項目文件夾下,若是要存儲到數據庫,就要使用數據模型數據庫
一、建立數據模型django
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'
複製代碼
二、在視圖類中使用後端
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('上傳成功')
複製代碼
三、最終在數據庫存儲的 瀏覽器
前面既然已經上傳成功了,那麼前端要顯示,就須要配置靜態文件路徑dom
一、在settings.py
中配置媒體的根目錄及根路由post
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
複製代碼
二、配置靜態文件路徑(項目的根路由中)url
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)
複製代碼
三、在瀏覽器中輸入http://localhost:8000/media/files/22.JPEG
spa
一、限制文件上傳類型
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'
複製代碼
二、修改上傳文件路徑(根據年/月/日來顯示)
...
file = models.FileField(upload_to='%Y/%m/%d', validators=[...
...
複製代碼
三、若是是僅僅是上傳圖片的話,能夠使用下面的
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'
複製代碼
一、定義一個通用的方法
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)
複製代碼
二、使用
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'
複製代碼