0

In my Python code, I received a file as InMemoryUploadedFile and then I'm trying to save that file on disk. It says that file stored successfully but when I try to open that file, I get this error:

File Opening Error

Here is the code snippet that I'm trying with

with Path("check.pdf").open(mode="wb") as output_file:
    output_file.write(fileToParse.read())

Another code that I tried before is this one:

outfd, filePath = tempfile.mkstemp(suffix='check.pdf', dir=os.getcwd())
with open(filePath, "wb") as dest:
    dest.write(fileToParse)
os.close(outfd)

In both cases, I get same error. I've checked different posts and even on here SO, first solution is working for many people. But I don't know why it is not storing proper file for me.

The type of file fileToParse that I received is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> and fileToParse.read() returns <class 'bytes'>

Can anyone tell me what am I doing wrong here?

Naila Akbar
  • 3,033
  • 4
  • 34
  • 76
  • An example PDF file perhaps if you want people to help you figure out what is happening? – David van Driessche Aug 06 '20 at 16:12
  • any kind of PDF file.. not working for anyone.. – Naila Akbar Aug 06 '20 at 16:49
  • I don't write python and even if I did I wouldn't want to take the time to create a test file to see what happens. I _am_ however quite familiar with the PDF file format. I'm not the only person like that on here I'm sure. A test file in such a case - especially because it's apparently so easy to generate - doesn't strike me as an impossible thing to add to your question. – David van Driessche Aug 06 '20 at 17:55

1 Answers1

0

I resolved my issue with the help of this Answer with minor changes. Here is the code that is working for me.

import tempfile, os

 outfd, filePath = tempfile.mkstemp(suffix=fileToParse.name, dir=os.getcwd())
 with open(filePath, 'wb+') as destination:
    for chunk in fileToParse.chunks():
        destination.write(chunk)    
 os.close(outfd)
Naila Akbar
  • 3,033
  • 4
  • 34
  • 76