保存上传的base64数据会导致TypeError:需要类似字节的对象,而不是“str” [英] Saving uploaded base64 data gives TypeError: a bytes-like object is required, not 'str'

查看:385
本文介绍了保存上传的base64数据会导致TypeError:需要类似字节的对象,而不是“str”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript库上传图片。它将图像数据放置在一个表单字段中,该表单字段是一个带有文件名和base64编码数据的JSON编码对象。



当我试图将图像保存在Flask中时,I得到这个错误:
$ b $ pre $ builtins.TypeError TypeError:需要类似字节的对象,而不是'str'

使用正确的名称创建映像文件,但数据已损坏,无法打开。如何保存上传的数据?




$ b

  app =烧瓶(__ name__)
UPLOAD_FOLDER = app.root_path +'/ images /'

@ app.route('/',methods = ['GET','POST'])
def index():
if request.method =='POST':
image_base = json.loads(request.form ['file'])['output'] ['image']
image_base = image_base [ image_base.find(',')+ 1:]
file_data = io.StringIO(image_base)
file = FileStorage(file_data,filename = json.loads(from_form)['output'] ['name '))
filename = secure_filename(file.filename)
file.save(os.path.join(app.config ['UPLOAD_FOLDER'],filename))
return redirect(url_for 'uploaded_file',filename = filename))

return render_template('index.html',methods = ['GET','POST'])





 文件/usr/local/lib/python3.5/site-packages /flask/app.py行1836,在__call__ 
返回self.wsgi_app(environ,start_response)
文件/usr/local/lib/python3.5/site-packages/flask/app.py,行1820,在wsgi_app
response = self.make_response(self.handle_exception(e))
在handle_exception中的文件/usr/local/lib/python3.5/site-packages/flask/app.py,第1403行
reraise(exc_type,exc_value,tb)
文件/usr/local/lib/python3.5/site-packages/flask/_compat.py,第33行,重新加注
raise值
在wsgi_app
响应= self.full_dispatch_request()
文件/usr/local/lib/python3.5/site-packages/flask/app.py,行1817 /usr/local/lib/python3.5/site-packages/flask/app.py,第1477行,在full_dispatch_request
rv = self.handle_user_exception(e)
文件/ usr / local /lib/python3.5/site-packages/flask/app.py,第1381行,在handle_user_exception
reraise(exc_type,exc_value,tb)
文件/ usr / local / lib / python3。 5 / site-packages / flask / _compat.py,第33行e
提高价值
文件/usr/local/lib/python3.5/site-packages/flask/app.py,第1475行,在full_dispatch_request
rv = self.dispatch_request( )
文件/usr/local/lib/python3.5/site-packages/flask/app.py,第1461行,在dispatch_request
返回self.view_functions [rule.endpoint](** req.view_args)
文件/Users/kr/PycharmProjects/instaup/instaup.py,第32行,在索引
file.save(os.path.join(app.config ['UPLOAD_FOLDER' ],文件名))
文件/usr/local/lib/python3.5/site-packages/werkzeug/datastructures.py,行2656,保存
copyfileobj(self.stream,dst, buffer_size)
文件/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shutil.py,第76行,位于copyfileobj
fdst.write(buf)
TypeError:需要类似字节的对象,而不是'str'


解决方案 代表一个字符串,而不是字节,你想 BytesIO 。 Base64编码的数据不是实际的图像字节,需要使用进行解码 b64decode

  file_data = io.BytesIO(b64decode (image_base))


I am using a JavaScript library to upload an image. It places the image data in a form field that is a JSON encoded object with the file name and base64 encoded data.

When I try to save the image in Flask, I get this error:

builtins.TypeError TypeError: a bytes-like object is required, not 'str'

The image file is created with the correct name, but the data is corrupt, I can't open it. How do I save the uploaded data?

app = Flask(__name__)
UPLOAD_FOLDER = app.root_path + '/images/'

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        image_base = json.loads(request.form['file'])['output']['image']
        image_base = image_base[image_base.find(',')+1:]
        file_data = io.StringIO(image_base)
        file = FileStorage(file_data, filename=json.loads(from_form)['output']['name'])
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))

    return render_template('index.html', methods=['GET', 'POST'])

  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/kr/PycharmProjects/instaup/instaup.py", line 32, in index
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  File "/usr/local/lib/python3.5/site-packages/werkzeug/datastructures.py", line 2656, in save
    copyfileobj(self.stream, dst, buffer_size)
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shutil.py", line 76, in copyfileobj
    fdst.write(buf)
TypeError: a bytes-like object is required, not 'str'

解决方案

StringIO represents a string, not bytes, you want BytesIO. Base64 encoded data is not the actual image bytes, it needs to be decoded with b64decode.

file_data = io.BytesIO(b64decode(image_base))

这篇关于保存上传的base64数据会导致TypeError:需要类似字节的对象,而不是“str”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆