如何将InMemoryUploadedFile的内容转换为字符串 [英] How to convert content of InMemoryUploadedFile to string

查看:1332
本文介绍了如何将InMemoryUploadedFile的内容转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何将Django2中上传的文件( InMemoryUploadedFile )的内容转换为字符串吗?

Does anyone know how to convert content of uploaded file (InMemoryUploadedFile) in Django2 to string?

I想知道如何编写以下 convert2string()

I want to know how to write the following convert2string():

uploaded_file = request.FILES['file']
my_xml = convert2string(uploaded_file)  # TODO write method(convert to xml string)
obj = MyObject()
parser = MyContentHandler(obj)
xml.sax.parseString(my_xml, parser)  # or xml.sax.parse(convertType(uploaded_file), parser)


推荐答案

尝试 str(uploaded_file.read())转换 InMemoryUploadedFile str

Try str(uploaded_file.read()) to convert InMemoryUploadedFile to str

uploaded_file = request.FILES['file']
print(type(uploaded_file))  # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
print(type(uploaded_file.read()))  # <class 'bytes'>
print(type(str(uploaded_file.read())))  # <class 'str'>



UPDATE-1

假设您要上传以下文本文件( .txt .json 等),


UPDATE-1
Assuming you are uploading a text file (.txt,.json etc) as below,

my text line 1
my text line 2
my text line 3

然后您的视图就像

then your view be like,

def my_view(request):
    uploaded_file = request.FILES['file']
    str_text = ''
    for line in uploaded_file:
        str_text = str_text + line.decode()  # "str_text" will be of `str` type
    # do something
    return something

这篇关于如何将InMemoryUploadedFile的内容转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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