0

I am writing a file upload page with Django/Python. I get this error: FileNotFoundError: [Errno 2] No such file or directory: '48.png'.

Here is the relevant part of the view, which handles the upload:

`if request.method == 'POST': 
    form = myform(request.POST, request.FILES)
    if form.is_valid(): 
        print("FORM VALID")
        f = request.FILES['thefile']
        print("f:" + f.name)
        print(pref+'/'+str(f))
        open(f.name, 'rb')
    else:
        print('FORM NOT VALID')

Things go wrong in the open(f.name statement. The form is in a template:

<form method="post" action="/dataset_storage_upload/{{ pk }}/{{pid}}/"      name="submit" enctype="multipart/form-data">
{% csrf_token %}
{{ theForm.as_p }}
<button type="start_upload" value="Submit"   onclick="document.upload.submit() ">Upload</button>
</form>

and this is the form:

class myform(forms.Form):
thefile = forms.FileField()

I have this information in the console

FORM VALID
f:48.png
/17/3/48.png

(/17/3 is the prefix)

In the Traceback, in the browser, under local vars, I have this:

pref    '/17/3'
mylist[] 
f   <InMemoryUploadedFile: 48.png (image/png)>
pk '17'
form    <myform bound=True, valid=True, fields=(thefile)>
request<WSGIRequest: POST '/dataset_storage_upload/17/3/'>

I think this tells me that there is a file 48.png in memory. So why is it not there when I open it?

Many thanks for your attention.

Old_Mortality
  • 519
  • 1
  • 4
  • 14

3 Answers3

0

It's only there in memory, not on the actual filesystem. Django File objects provide a wrapper around both real files, and in-memory files.

For example, if you were handling a file that was coming from a FileField on some model, what you're doing would work, but the file you're handling doesn't yet exist on the system.

If you want to read the file in your view, you can just call File.read:

f = request.FILES['thefile']
contents = f.read()
csinchok
  • 741
  • 3
  • 10
0

By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory. This means that saving the file involves only a read from memory and a write to disk and thus is very fast.

Aviah Laor
  • 3,620
  • 2
  • 22
  • 27
0

I changed f.open( into f.read( and now it works perfectly. For completeness: My goal is to store the uploaded file in S3, so that now I do

s3.Object('mybucket', str(pk)+'/'+str(p)+'/'+str(f)).put(Body=f.read(),Metadata={'project': '17','dataset':'3','filename':str(f)})

and this works.

Old_Mortality
  • 519
  • 1
  • 4
  • 14