天天看點

在django中 使用 jq上傳檔案

使用jq上傳檔案的demo

本文章是用jq在基于python3 Django2.1 實作的簡單上傳檔案的功能

第一次寫文章,有哪裡出問題了,請各位大佬多多教導!

1.建立django項目

在pycharm 左上角File >New Project > Django >選擇環境(隻要安裝有的話一般預設就行【my_django_project1】是本次項目的名字)>Create

在django中 使用 jq上傳檔案

2.建立app

在底部打開pycharm 的指令行工具Terminal:輸入python manage.py startapp mydemo2

3.配置url

1.在mydemo2 的app下建立urls.py,然後在my_django_project1的檔案夾下導入這個urls.py

在django中 使用 jq上傳檔案

2.在mydemo2 的app下的urls中配置url連結及在view.py 中配置處理請求的視圖函數

在django中 使用 jq上傳檔案
在django中 使用 jq上傳檔案

3.在指令行工具Terminal 中輸入:python manage.py runserver 運作項目

在浏覽器中輸傳入連結接檢視效果okok

在django中 使用 jq上傳檔案

4.将view中的get的HttpResponse(“okoko”)換成render(request,‘mydemo2/index.html’,{})

index.html 是我事先在bootstrap 官網上複制的模闆,在浏覽器中輸傳入連結接檢視效果

在django中 使用 jq上傳檔案
在django中 使用 jq上傳檔案

4.jq 上傳檔案

1.在index.html 中加入

<form id="mydemo2" enctype="multipart/form-data">
          <input type="file" name="upfile" id="upfile" value="">
          
        <button class="btn btn-success" onclick="func1">上傳</button>
 </form>
           

當然要事先導入

<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" target="_blank" rel="external nofollow" >
<script src="/static/js/jquery-1.12.4.js"></script>
           

效果圖:

在django中 使用 jq上傳檔案

2.func1 ajax上傳檔案的代碼

function func1(){
         var file=$("#upfile")[0].files[0]
         var formData=new FormData()
         formData.append('upfile',file)
         $.ajax({
             type:"post",
             url:'upfile/',
             data: formData,
             processData: false,
             contentType: false,
             success:function (data) {
                 console.log(data)
             },
             error:function (xhr) {
                 console.log(xhr)
             }
         })
     }
           

3.在mydemo2 的urls.py 中添加

re_path(r'^upfile/$',mydemo2.My_handle.as_view(),name="upfile"),
           

4.在mydemo2 中的view.py 中

class My_handle(View):
    def get(self,request):

        return render(request,'mydemo2/index.html',{})

    def post(self,request):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        if request:
            file_object=request.FILES.get('upfile') #擷取前端上傳的檔案
            print(file_object.name)
            #建立儲存路徑
            path=os.path.join(BASE_DIR,'mydemo2/db/{}'.format(file_object.name))
            path=path.replace('\\','/')
            if os.path.exists(path):
                #如果檔案存在 就不處理。。
               return HttpResponse(" file already exists!")
            else:
                f=open(path,'wb+')
                #分段把檔案寫入到路徑中
                for chunk in file_object.chunk():
                    f.write(chunk)
                f.close()
                return HttpResponse("file save ok!!")
           

最後就能在mydemo2 下的db檔案夾下看見上傳的檔案了

在django中 使用 jq上傳檔案

還有很多細節處理不好,下次再改進!!!

倉庫連結: https://gitee.com/htg_nice/my_django_demo19-4-3.git

繼續閱讀