从表单上传文件到S3

时间:2017-03-05 20:30:58

标签: python amazon-s3 flask

我是s3的新手,并试图上传一些文件,但我得到The system cannot find the file specified: <hashed_file_name>.jpg我理解这个问题。当文件保存在根目录下时,一切都很好。但我不想保存文件。我想在action的{​​{1}}之后直接上传。

form

感谢您的帮助。

编辑1:

{#重编辑#}

def upload_to_s3(file_to_upload, s3_upload_folder):
    s3 = boto3.resource('s3',
                    aws_access_key_id=app.config['ACCESS_KEY_ID'],
                    aws_secret_access_key=app.config['SECRET_ACCESS_KEY'])

    s3.meta.client.upload_file(file_to_upload, app.config['BUCKET_NAME'], s3_upload_folder)


def _user_img_folder(form, file_name):
    username = session['name']
    vacation_name = slugify(form.test_name.data)
    directory = os.path.join(username, test_name)
    directory = os.path.join(UPLOAD_FOLDER, directory)
    return directory + '/' + file_name


@app.route('/post', methods=['GET', 'POST'])
def test():
    if _is_image():
        uploaded_images = request.files.getlist('photo')
        for image in uploaded_images:
            processed_image_name = _hash_image_name(image) # Returns hashed filename with extension
            directory = _user_img_folder(form, processed_image_name)
            upload_to_s3(str(processed_image_name), str(directory))
    return render_template('test.html', form=form, error=error)

1 个答案:

答案 0 :(得分:0)

找到答案:

我已经改变了

s3.meta.client.upload_file(file_to_upload, app.config['BUCKET_NAME'], s3_upload_folder)

为:

s3.Object(app.config['BUCKET_NAME'], s3_upload_folder).put(Body=image)

所以诀窍是,您必须将文件放在磁盘上并提供filepath file_to_upload或提供文件本身,如我在此答案中所示。