Django中上傳的檔案,除了使用普通的方式接收外,還可以通過ORM模型來自動接收,
前端檔案提交
下面是一種較為通用的檔案提交方式,這種方式需要注意,form標簽的enctype屬性值必須為multipart/form-data,用于檔案提交的input標簽的type屬性值也必須是file,當然,請求method也需要是post,
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" name="提交">
</form>
普通方式上傳檔案
普通的檔案接收方式就是將request.FILES中的檔案物件獲取出來再手動寫入一個新的檔案即可,
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
# 新建一個視圖
class IndexView(View):
# 回傳檔案上傳的界面
def get(sel, request):
return render(request, 'index.html')
# 獲取上傳的檔案,并保存到新的檔案中
def post(self, request):
myfile = request.FILES.get('myfile')
with open('somefile.txt', 'wb') as fp:
for chunk in myfile.chunks():
fp.write(chunk)
return HttpResponse('success!')
使用ORM模型自動接收
這種方式需要在ORM模型中定義一個models.FileField欄位,并指定upload_to引數,此引數為檔案存放的目錄路徑,是一個相對于專案根目錄的相對路徑,upload_to引數除了直接指定路徑名外,還可以使用當前日期來指定路徑,如%Y/%m/%d/表示根據當前的年月日資訊新建三層目錄,上傳的檔案就放在此目錄下(字串中的斜杠表示路徑分隔符),指定的目錄不存在的話,會自動新建,
注1:如果在settings.py中配置了MEDIA_ROOT,則默認會將上傳的檔案放在此目錄下,如果同時也指定了uplodad_to引數,則會在此目錄下再新建對應目錄來存放檔案,
注2:如果要上傳圖片,可以使用models.ImageField欄位,用法和models.FileField是一樣的,使用這個欄位時,如果提示安裝Pillow庫,則按提示安裝即可,Django中處理圖片需要用到這個庫,安裝方法:pip install pillow,
from django.db import models
# 隨意新建一個ORM模型
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
file = models.FileField(upload_to='upload_files')
# 可以按照日期來新建目錄,注意斜杠表示目錄分隔,%Y/%m/%d/會新建三層目錄
# file = models.FileField(upload_to='%Y/%m/%d/')
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
from .models import Article
class IndexView(View):
def get(self, request):
return render(request, 'index.html')
def post(self, request):
title = request.POST.get('title')
content = request.POST.get('content')
# 獲取檔案并使用ORM模型來進行自動保存
file = request.FILES.get('myfile')
# 除了會將提交資訊保存到資料庫中,還會自動將檔案保存到upload_to引數指定的目錄下
Article.objects.create(title=title, content=content, file=file)
return HttpResponse('success!')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/180416.html
標籤:其他
