简体   繁体   中英

Can't put image filed to Amazon s3 in Python Flask

I want to upload an image file on Flask + Amazon s3 but this error occurs:

在此处输入图片说明

Actually I have s3 to be in public. But after uploading the image, this can't get...

My code:

import os

import io
import boto3
from flask import Flask, flash, request, redirect, url_for, current_app
from werkzeug.utils import secure_filename

basedir = os.path.abspath(os.path.dirname(__file__))

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in current_app.config["ALLOWED_EXTENSIONS"]

def uploads_file(request):
    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        s3_bucket = current_app.config['S3_BUCKET']
        s3_dir = current_app.config['S3_DIR']
        s3 = boto3.client('s3', region_name = 'us-west-1')
        response = s3.put_object(
            Body = io.BufferedReader(file).read(),
            Bucket = s3_bucket,
            Key = f'{s3_dir}/{filename}'
        )
        return filename

I have added app/.aws/credentials .

aws_access_key_id=XXXXXXXXXX
aws_secret_access_key=XXXXXXXXXXXXXXXXX

You can also pass credentials when you create s3 client. Something like this should work:

client = boto3.client(
    's3',
    aws_access_key_id=key_id,
    aws_secret_access_key=access_secret,
    region_name='us-west-1',
)

with open(path, 'rb') as src:
    client.put_object(
        ACL='public-read',
        Bucket=bucket_name,
        Key=filename,
        Body=src
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM