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

kqqjbcuj  于 2023-02-10  发布在  Go
关注(0)|答案(3)|浏览(170)

有人知道如何在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)
vfhzx4xs

vfhzx4xs1#

尝试使用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'>
    • 更新-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
nlejzf6q

nlejzf6q2#

内存中的文件-〉内存中已上载文件

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

dojqjjoe3#

如果您想以列表的形式读取文件数据,那么您可以尝试以下代码:

uploaded_file = request.FILES['file'] 
file_data = uploaded_file.read().decode().splitlines()  # get each line data as list item

相关问题