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

2024/11/15 9:03:12

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.

Answer

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 POSTand the <form> that posted the request has the attributeenctype="multipart/form-data". Otherwise, request.FILES will be empty.

https://en.xdnf.cn/q/71482.html

Related Q&A

ImportError: cannot import name AutoModelWithLMHead from transformers

This is literally all the code that I am trying to run: from transformers import AutoModelWithLMHead, AutoTokenizer import torchtokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small&…

UnicodeEncodeError: ascii codec cant encode characters in position 0-6: ordinal not in range(128)

Ιve tried all the solution that I could find, but nothing seems to work: teext = str(self.tableWidget.item(row, col).text())Im writing in greek by the way...

selenium PhantomJS send_keys doesnt work

I am using selenium and PhantomJS for testing. I followed Seleniums simple usage, but send_keys doesnt work on PhantomJS, it works on Firefox. Why? I have to use button.click() instead?#!/usr/bin/pyt…

Replace values in column of Pandas DataFrame using a Series lookup table

I want to replace a column of values in a DataFrame with a more accurate/complete set of values generated by a look-up table in the form of a Series that I have prepared.I thought I could do it this wa…

Behavior of round function in Python

Could anyone explain me this pice of code:>>> round(0.45, 1) 0.5 >>> round(1.45, 1) 1.4 >>> round(2.45, 1) 2.5 >>> round(3.45, 1) 3.5 >>> round(4.45, 1) 4.5…

Pygame application runs slower on Mac than on PC

A friend and I are making a game in Python (2.7) with the Pygame module. I have mostly done the art for the game so far and he has mostly done the coding but eventually I plan to help code with him onc…

How to extract feature vector from single image in Pytorch?

I am attempting to understand more about computer vision models, and Im trying to do some exploring of how they work. In an attempt to understand how to interpret feature vectors more Im trying to use …

Which language should I use for Artificial intelligence on web projects

I have to do one project for my thesis involving Artificial intelligence, collaborative filtering and machine learning methods.I only know PHP/mysq/JS, and there is not much AI stuff examples in PHP.Th…

Scrapy with selenium, webdriver failing to instantiate

I am trying to use selenium/phantomjs with scrapy and Im riddled with errors. For example, take the following code snippet:def parse(self, resposne):while True:try:driver = webdriver.PhantomJS()# do so…

How do I enable TLS on an already connected Python asyncio stream?

I have a Python asyncio server written using the high-level Streams API. I want to enable TLS on an already established connection, as in STARTTLS in the SMTP and IMAP protocols. The asyncio event loop…