django 開發之檔案上傳

來源:互聯網
上載者:User

標籤:

建立一個檔案夾用於儲存上傳的路徑

然後在setting 裡面設定檔的上穿的路徑

#設定檔的上傳路徑
MEDIA_URL=‘/uploads‘
MEDIA_ROOT= os.path.join(BASE_DIR,‘uploads‘)

接著在url裡面配置使用者映像上傳的路由

 

解決富文字編輯器的圖片長傳問題:

首先要做的就是建立一個upload  python 檔案 在你的app下建立、

具體的代碼如下

 1 # -*- coding: utf-8 -*- 2 from django.http import HttpResponse 3 from django.conf import settings 4 from django.views.decorators.csrf import csrf_exempt 5 import os 6 import uuid 7 import json 8 import datetime as dt 9 #這個裝飾器用於不再進行表單驗證提交10 @csrf_exempt11 def upload_image(request, dir_name):12     ##################13     # 這是kindeditor想要的格式14     #  kindeditor圖片上傳返回資料格式說明:15     # {"error": 1, "message": "出錯資訊"}16     # {"error": 0, "url": "圖片地址"}17     ##################18     result = {"error": 1, "message": "上傳出錯"}19     #imgFile來自於富文字編輯器查看源碼之後找到的它定義的檔案名稱字20     files = request.FILES.get("imgFile", None)21     if files:22         result =image_upload(files, dir_name)23     return HttpResponse(json.dumps(result), content_type="application/json")24 25 #目錄建立26 def upload_generation_dir(dir_name):27     today = dt.datetime.today()28     dir_name = dir_name + ‘/%d/%d/‘ %(today.year,today.month)29     if not os.path.exists(settings.MEDIA_ROOT + dir_name):30         os.makedirs(settings.MEDIA_ROOT + dir_name)31     return dir_name32 33 # 圖片上傳34 def image_upload(files, dir_name):35     #允許上傳檔案類型36     allow_suffix =[‘jpg‘, ‘png‘, ‘jpeg‘, ‘gif‘, ‘bmp‘]37     file_suffix = files.name.split(".")[-1]38     if file_suffix not in allow_suffix:39         return {"error": 1, "message": "圖片格式不正確"}40     relative_path_file = upload_generation_dir(dir_name)41     path=os.path.join(settings.MEDIA_ROOT, relative_path_file)42     if not os.path.exists(path): #如果目錄不存在建立目錄43         os.makedirs(path)44     file_name=str(uuid.uuid1())+"."+file_suffix45     path_file=os.path.join(path, file_name)46     file_url = settings.MEDIA_URL + relative_path_file + file_name47     #寫入操作,二進位形式,最終完成上傳,真正儲存圖片48     open(path_file, ‘wb‘).write(files.file.read())49     return {"error": 0, "url": file_url}
View Code

 

然後我們在url 裡面寫入路由

最後我們要在富文字編輯器裡面寫入路徑

 

 

 

 

 


django 開發之檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.