【问题标题】:File size is zero when uploading to Google Drive with Python and Flask使用 Python 和 Flask 上传到 Google Drive 时文件大小为零
【发布时间】:2019-02-16 09:52:38
【问题描述】:

我正在尝试将 Google Drive API 与 Flask 结合起来将文件上传到 Google Drive。要上传文件,我使用以下代码:

@app.route('/upload_google', methods=['GET','POST'])
def upload_google():
    if not google.authorized:
        return redirect(url_for("google.login"))
    file = request.files['myfile']
    filename = secure_filename(file.filename)
    para = {
        "name": filename,
        'mimeType':'image/jpeg',
    }
    files = {
        'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
        'file': request.files['myfile']
    }
    uploaden = google.post(
        "upload/drive/v3/files",
        files=files,
    )
    print (uploaden.text)
    return('upload  succesfull')

在 HTML 模板中,我使用以下形式:

<form method=POST enctype=multipart/form-data action="upload_google">
<input type=file name=myfile>
<input type=submit>
</form>

将文件上传到 Google 有效,唯一的问题是上传的文件没有文件大小,我不知道为什么。

【问题讨论】:

    标签: python post flask file-upload google-drive-api


    【解决方案1】:

    先将文件保存在本地,然后在标题中打开,即可解决问题:

    @app.route('/upload_google', methods=['GET','POST'])
    def upload_google():
        if not google.authorized:
            return redirect(url_for("google.login"))
        file = request.files['myfile']
        filename = secure_filename(file.filename)
        UPLOAD_FOLDER = ''
        app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        para = {'name': filename,
                'mimeType': mimetype}
        files = {'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),'file':(filename, open(UPLOAD_FOLDER+'/'+filename,'rb'), mimetype,{'Expires': '0'})}
        r = google.post('https://www.googleapis.com/upload/drive/v3/files',files=files)
        return redirect("/drive")
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      相关资源
      最近更新 更多