天天看點

django接收并儲存前端el-upload傳遞的檔案

前端代碼

<el-upload
        class="upload-demo"
        ref="upload"
        action="/api/v1/yw-sql"  // 接口位址
        multiple
        :headers="importHeaders" // 添加請求頭token
        :on-preview="handlePreview" // 點選已上傳的檔案連結時的鈎子, 可以通過 file.response 拿到服務端傳回資料
        :on-remove="handleRemove" // 删除時的鈎子
        :file-list="fileList"
        :auto-upload="false">  // 是否自動上傳
        <el-button slot="trigger" size="small" type="primary">選取檔案</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到伺服器</el-button>
        <div slot="tip" class="el-upload__tip">隻能上傳SQL檔案,且不超過100M</div>
      </el-upload>           

後端代碼

def post(self, request):
        """接收檔案"""
        try:
            files = request.FILES.getlist("file",None) # 接收前端傳遞過來的多個檔案
            for file in files:
                sql_path = f"{os.getcwd()}/sql/{file.name}"
                # 寫入檔案
                with open(sql_path, 'wb') as f:
                    for content in file.chunks():
                        print(content)
                        f.write(content)
            return JSONApiResponse()
        except Exception as e:
            return JSONApiResponse(code=401, msg=str(e))