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))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章