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

Koh*_*URA 8 django python-3.x

有谁知道如何将InMemoryUploadedFileDjango2中上传文件 ( ) 的内容转换为字符串?

我想知道如何写以下内容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)
Run Code Online (Sandbox Code Playgroud)

JPG*_*JPG 15

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

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'>
Run Code Online (Sandbox Code Playgroud)


UPDATE-1
假设您上传文本文件(.txt.json等),如下,

my text line 1
my text line 2
my text line 3
Run Code Online (Sandbox Code Playgroud)

那么你的观点就像,

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
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但是 `str(uploaded_file.read())` 不适用于 `ValueError`,`unknown url type: "b''"`。 (2认同)