Django之文件上傳

1:文件上傳是網站中常見的功能,通常用form表單來提交:html

HTMLdjango

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <input type="submit">
</form>

viewpost

from django.shortcuts import render,HttpResponse
from django.views.generic import View
from .forms import IndexFrom
class IndexView(View):

    def get(self,request):
        return render(request,"index.html")

    def post(self,request):
        myfile = request.FILES.get("myfile")  //接收file文件
        with open("aa.txt","wb") as fp:   
            for chunk in myfile.chunks():
                fp.write(chunk)
        return HttpResponse("ok")

  結果會在項目目錄中多了一個aa.txt文件網站

  2:使用模型來處理上傳文件url

  model:spa

class Article(models.Model):
    title = models.CharField(max_length=20)
    content = models.CharField(max_length=100)
    thumbnail = models.FileField(upload_to="files")   //定義一個FileField字段,upload_to表示上傳來的文件放在哪一個文件夾也能夠(upload_to="%Y%m%d")

view:code

  def post(self,request):
        title = request.POST.get("title")
        content = request.POST.get("content")
        thumbnail = request.FILES.get("myfile")  //獲取文件
        article = Article.objects.create(title=title,content=content,thumbnail=thumbnail)
        article.save()
        return HttpResponse("ok")

  3指定MEDIA_ROOT和MEDIA_URL:orm

  在setting中添加這兩個字段:htm

  

MEDIA_ROOT = os.path.join(BASE_DIR,"media")        //表示長傳的文件存放的目錄(就能夠再也不upload_to中設置l)
MEDIA_URL = "/media/"   //訪問這個文件的路徑

url.py 須要設置路徑:blog

from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path("",views.IndexView.as_view())
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

  4限制文件拓展名:

  

from django.db import models
from django.core import validators

class Article(models.Model):
    title = models.CharField(max_length=20)
    content = models.CharField(max_length=100)
    thumbnail = models.FileField(upload_to="%Y/%m/%d",validators=[validators.FileExtensionValidator(["txt","pdf"])])  //經過validator來限制

  5上傳圖片:(上傳圖片須要安裝Pillow庫)(pip install Pillow)

  

 images = models.ImageField(upload_to="files")   //方法和上面同樣
相關文章
相關標籤/搜索