用python寫一個簡單的文件上傳


  用Pycharm創建一個django項目。目錄如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>upload</title>
 6 </head>
 7 <body>
 8 {# 上傳文件的form表單必須要加上enctype="multipart/form-data" #}
 9 <form action="/upload/" method="post" enctype="multipart/form-data">
10     <input type="file" name="upload_files">
11     <input type="submit" value="提交">
12 </form>
13 </body>
14 </html>
uploadFiles.html
 1 from django.shortcuts import render,HttpResponse
 2 
 3 # Create your views here.
 4 
 5 # CBV方式(class base views)
 6 from django.views import View
 7 class Upload(View):
 8     def post(self,request):
 9         '''
10         保存上傳文件前,數據需要存放在某個位置。默認當上傳文件小於2.5M時,django會將上傳文件的全部內容讀進內存。從內存讀取一次,寫磁盤一次。
11         但當上傳文件很大時,django會把上傳文件寫到臨時文件中,然后存放到系統臨時文件夾中。
12         :param request:
13         :return:
14         '''
15         # 從請求的FILES中獲取上傳文件的文件名,file為頁面上type=files類型input的name屬性值
16         filename = request.FILES['upload_files'].name
17         # 在項目目錄下新建一個文件
18         with open(filename,'wb') as f:
19             # 從上傳的文件對象中一點一點讀
20             for chunk in request.FILES['upload_files'].chunks():
21                 # 寫入本地文件
22                 f.write(chunk)
23         return HttpResponse('上傳ok')
24 
25     def get(self,request):
26         return render(request, 'uploadFiles.html')
views.py
 1 """day67 URL Configuration
 2 
 3 The `urlpatterns` list routes URLs to views. For more information please see:
 4     https://docs.djangoproject.com/en/2.2/topics/http/urls/
 5 Examples:
 6 Function views
 7     1. Add an import:  from my_app import views
 8     2. Add a URL to urlpatterns:  path('', views.home, name='home')
 9 Class-based views
10     1. Add an import:  from other_app.views import Home
11     2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
12 Including another URLconf
13     1. Import the include() function: from django.urls import include, path
14     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
15 """
16 from django.contrib import admin
17 from django.urls import path
18 from app01 import views
19 
20 urlpatterns = [
21     path('upload/',views.Upload.as_view() ),
22 ]
urls.py

  注意settings.py中的這一行要注釋掉

'django.middleware.csrf.CsrfViewMiddleware',

  點擊運行,文件會上傳到項目的根目錄下面。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM