简体   繁体   English

Boto3和dropzone.js的S3图片上传错误

[英]S3 image upload error with boto3 and dropzone.js

using this API i am able to upload the file to S3 using Postman. 使用此API,我可以使用Postman将文件上传到S3。

i gave direct path to the file "/home/user/Downloads/black-rose.png" 我给出了文件“ /home/user/Downloads/black-rose.png”的直接路径

header_logo = request.data['header_logo']

#local file path
data = open(header_logo, 'rb')

s3 = boto3.resource(
     's3',
     aws_access_key_id=ACCESS_KEY_ID,
     aws_secret_access_key=ACCESS_SECRET_KEY,
     config=Config(signature_version='s3v4')
 )
#generatre a random url
header_logo = "header_logo/" + get_random_string(length=20) + ".png"

#AWS foler & file name with public access
s3.Bucket(BUCKET_NAME).put_object(Key=header_logo, ContentType = 'image/png', Body=data, ACL='public-read')

when i give the direct file path its working, but my front end developer says he cant give direct file path using javascript so he is using a plugin "dropzonejs" to encrypt the file path which gives file like like this 当我给直接文件路径提供工作时,但是我的前端开发人员说他无法使用javascript提供直接文件路径,因此他正在使用插件“ dropzonejs”来加密文件路径,从而得到这样的文件

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElEQVR4Xoy9B7hlZ3Xe/9u9nH5uL3OnabqkkTTqCFVAgA2SwQaX4GATHIc/DiFg

which on directly giving this data to the api throws error 直接将此数据提供给api会引发错误

You simply need to decode the base 64 representation of the image, and then upload the decoded result, note that the start of the string up to the firs comma is not actually part of the image, you need to trim the prefix. 您只需要解码图像的base 64表示形式,然后上传解码结果,请注意,直到firs逗号的字符串的开头实际上不是图像的一部分,您需要修剪前缀。

import base64

image_string = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElEQVR4Xoy9B7hlZ3Xe/9u9nH5uL3OnabqkkTTqCFVAgA2SwQaX4GATHIc/DiFg"

image_encoded = image_string[image_string.index(',') + 1:]

image_data = base64.b64decode(image_encoded)

Then you can upload to s3 the data of the image 然后您可以将图像数据上传到s3

s3.Bucket(BUCKET_NAME).put_object(Key=header_logo, ContentType = 'image/png', Body=image_data, ACL='public-read')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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