Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert content of InMemoryUploadedFile to string

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

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)
like image 790
Kohei TAMURA Avatar asked May 25 '18 04:05

Kohei TAMURA


2 Answers

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
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
like image 174
JPG Avatar answered Sep 17 '22 13:09

JPG


file_in_memory -> InMemoryUploadedFile

file_in_memory.read().decode() -> txt output
like image 27
Aleksei Khatkevich Avatar answered Sep 16 '22 13:09

Aleksei Khatkevich