有没有人知道如何将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)
答案 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