美文网首页
django实现文件上传

django实现文件上传

作者: Gswu | 来源:发表于2019-06-13 20:36 被阅读0次

新建 html 页

app 名称为blog

在templates/blog 下新建 upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="row">
      <div class="col-md-8 col-md-offset-2">
          <form class="form-inline" role="form"  method="post" enctype="multipart/form-data" accept-charset="utf-8">
             {% csrf_token %}
              <div class="form-group">
                  <input type="file" name="file">
              </div>
              <div class="form-group">
                  <input type="submit" value="上传文件">
              </div>
          </form>
      </div>
  </div>

</body>
</html>

blog 下 views.py 中添加处理方法

import os
from django.http import HttpResponse,Http404
from django.shortcuts import render

# 处理上传上来文件的方法,
def upload_file(request):
    if request.method=="POST":
        handle_upload_file(request.FILES['file'],str(request.FILES['file']))
        return HttpResponse('Successful')
    return render(request,'blog/upload.html')

# 文件保存到指定路径
def handle_upload_file(file,filename):
    path='media/uploads/'
    if not os.path.exists(path):
        os.makedirs(path)
    with open(path+filename,"wb+")as dest:
        for chunk in file.chunks():
            dest.write(chunk)

编写 urls.py 增加路由

from django.urls import path,include
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.index, name='index'),
    path('index01/', views.index01, name='index01'),
    path('index02/<int:author_id>/', views.index02, name='index02'),
    path('upload/', views.upload_file, name='upload'),
]

测试

访问 127.0.0.1:8000/blog/upload/
上传文件,文件就会保存到项目下的media/uploads 文件夹

相关文章

网友评论

      本文标题:django实现文件上传

      本文链接:https://www.haomeiwen.com/subject/nepefctx.html