使用Python和Flask上传到Google云端硬盘时,文件大小为零

时间:2018-09-11 20:14:19

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

我正在尝试将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是可行的,唯一的问题是文件上传时没有文件大小,我不知道为什么。

1 个答案:

答案 0 :(得分:0)

通过首先在本地保存文件然后在标题中打开文件来解决问题:

@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")