Django+vue はフォルダーのアップロードを実装します。超シンプルなバージョン (プロテスト効果的)

最近、django でファイルのアップロードとアップロードを学びました。インターネット上にはフォルダーのアップロードとダウンロードがまったくありません。いくつか見つけましたが、多くのエラーが報告されました。どれも使用できません。次の方法は私が実際に使用した方法ですので、共有します。

フロントエンドのビューは非常にシンプルで、テンプレート部分は

<input type="file" id="twos" webkitdirectory/>
<el-button type="primary" @click="sumfolder">文件夹提交</el-button>

必要なのは 2 つだけです。1 つはフォルダーを選択するための inout、もう 1 つはボタンをクリックしてファイルをアップロードするためです。

コードの js 部分は次のとおりです。

async sumfolder() {
      //拿到元素节点
      let twos=document.getElementById('twos')
      //读取dom节点图片
      const file = twos.files
      //声明一个对象,传递图片用
      let obj=new FormData()
       //循环将图片读入formdata,并且给个不同的'flies'+i,不然会被覆盖
      for(let i=0;i<file.length;i++){
        console.log(file[i])
        obj.append('flies'+i,file[i])
      }
      
      //也可以传递一些其他表单信息  obj.append('admin_id','admin_id')【可选项】
      //我这里axios封装了成了this.$http,你们也可以直接替换this.$http成为axios.post({})效果一样
      const { data: res } = await this.$http({
          url:"http://127.0.0.1:8000/rotate/",
          method: "POST",
          data:obj,
          headers:{'content-type':'application/x-www-form-urlencoded'}
          
     });

vue の上記部分はすべて完了しました

これが Django の部分です。非常に簡単です

import os
from pathlib import Path
from django.shortcuts import HttpResponse,render

#旋转操作
def rotate(request):
    BASE_DIR = Path(__file__).resolve().parent.parent
    if request.method == 'POST':
        print(request.FILES)
        if request.FILES:
            for i in request.FILES:
                myFile = request.FILES[ i ]
                if myFile:
                    dir = os.path.join(os.path.join(BASE_DIR, 'img\\static'), 'upload') #这里自己配好要保存的路径
                    destination = open(os.path.join(dir, myFile.name),
                                       'wb+')
                    for chunk in myFile.chunks():
                        destination.write(chunk)
                    destination.close()
    return HttpResponse('ok')

終了した!できました!

おすすめ

転載: blog.csdn.net/qq_43644046/article/details/131101572