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.
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
FILESis the name from the<input type="file" name="" />. Each value inFILESis anUploadedFile.
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.FILESwill only contain data if the request method wasPOSTand the<form>that posted the request has the attributeenctype="multipart/form-data". Otherwise,request.FILESwill be empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With