Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django- How do I read a file from an input file tag?

Tags:

python

django

I don't want the file to be saved on my server, I just want the file to be read and printed out in the next page. Right now I have this.

(index.html)
    <form name="fileUpload" method="post">
        <input type="file" />
        <input type="submit" value="Submit" />
    </form>

And I'm trying to do something like this-

def upload_file(request):
    if request.method == "POST":
        upload = request.POST.get('fileUpload').read()
        return render(request, 'directory/return.html', {'output': upload})
    else:
        return render(request, 'directory/index.html')

But obviously that just doesn't work. I want it to work for text files and csv files.

Thank you.

like image 692
Ravaal Avatar asked Sep 18 '15 15:09

Ravaal


1 Answers

Firstly, there are some things missing in your form which you will have to add.

To upload files using a form, you’ll need to define the enctype as "multipart/form-data" in the <form> element. Also, the file input element should have the name attribute in it

index.html

<form enctype="multipart/form-data" action="/my/url/" method="post"> # define the enctype
    <input type="file"  name="my_uploaded_file"/> # define a 'name' attribute 
    <input type="submit" value="Submit" />
</form>

Then, in your views, you can access the uploaded file using request.FILES dictionary. As per request.FILES docs:

Each key in FILES is the name from the <input type="file" name="" />. Each value in FILES is an UploadedFile.

You can access the uploaded file using my_uploaded_file key in the request.FILES dictionary.

views.py

def upload_file(request):
    if request.method == "POST":
        my_uploaded_file = request.FILES['my_uploaded_file'].read() # get the uploaded file
        # do something with the file
        # and return the result            
    else:
        return render(request, 'directory/index.html')

Note:

request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

like image 76
Rahul Gupta Avatar answered Oct 13 '22 22:10

Rahul Gupta