如何将InMemoryUploadedFile的内容转换为字符串

时间:2018-05-25 04:42:21

标签: django python-3.x

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

我想知道如何编写以下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)

2 个答案:

答案 0 :(得分:1)

尝试str(uploaded_file.read())InMemoryUploadedFile转换为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等),如下所示,

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

然后你的观点就像,

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

答案 1 :(得分:0)

file_in_memory-> InMemoryUploadedFile

file_in_memory.read().decode() -> txt output