5 Easy Ways to Upload a File Using Python

  • Updated on December 5, 2022
  • Tech

Every developer should be familiar with the vital use of file uploading. 

Most software programs need file uploading to perform specific tasks, and a Python file upload technique comes in handy most of the time. 

This article provides five ways to upload a file using Python.

Use Python’s OS Module

python-OS-module

You can configure various characteristics on an HTML form, such as the action attribute, which determines to which URL the provided data will be sent. An HTML form has to have the encrypt attribute multi-part/form-data to allow file uploading. 

Secondly, we must use the HTML input tag and assign its value to “file.” This augments the form’s input button with an upload button. The code snippet below well illustrates it:

<html>
<body>
  <form enctype = “multipart/form-data” action = “python_upload.py” method = “post”>
      <p>Upload Your File: <input type = “file” name = “uploaded_filename” /></p>
      <p><input type = “submit” value = “Upload File” /></p>
  </form>
</body>
</html>

Whenever a file is uploaded by the user, the attribute action in the code above runs a Python script. The field storage object receives the submitted file name from the form’s “uploaded_filename” on the server as the Python script processes the uploaded data. 

All that is left for the server to do at this point is read the uploaded file and put it into the “fileitem.” After this entire process, the uploaded file will now be saved to the server.

The Python script resembles the following code in specific ways:

import os
fileitem = form[‘filename’]

if file_item.filename:

    fn = os.path.basename(file_item.filename)

    open(fn, ‘wb’).write(file_item.file.read())

Use Python’s Requests Library for a Single File

Another way to upload files using Python is to use the Python requests library. It’s better to install the request library in a virtual environment. 

By enabling a virtual environment, we can restrict this Python installation from affecting the global installation. Create a virtual environment and activate it using the following commands.

python3 -m venv
. bin/activate

Then install the requests library using the pip package manager.

pip install requests

Now let’s start the coding part. Create a new file called file_upload.py and import the requests library into that file:

import requests

To upload a file, we need to allow the program to open that file and stream it. For that, we have to give the necessary permission for the code. We can do it with the open() function. open() functions accept two parameters called file path and mode. 

For example, if we give the value “rb” to mode, it means “read binary” value. This argument informs the system that we intend to open the document in read-only mode and that we want to use its binary data:

file = open(“filename.txt”, “rb”)

Please take note that reading the file in binary mode is crucial to reliably calculate the content length of the file when it’s sent over a network.

Next, we need a destination to send our files. There is a free service called httpbin that you can use to test HTTP requests. So let’s use it in our example. We have to assign the URL of it to a variable.

url = “http://httpbin.org/post”

How to Submit the Request?

Our next step is to submit the request using the post() method of the requests library. We need to provide the “server’s URL” and the “files” property in this function. We already assigned the server’s url to the “url” variable. The “files” property is a dictionary that includes a key and value. 

As you saw in our first example, an HTML form accepts the file. The variable called “name” in the input field is the key of the “files” property. Bytes from the file that you want to upload make up the value.

We already assigned that to the “file” variable above. Finally, we save the response of our request to a variable.

response = requests.post(url, files = {“form_field_name”: file})

In order to evaluate whether your post() operation was successful, we often look at the HTTP code response. We can get the advantage of the response object’s test URLs ok field. If so, we’ll print the response from the HTTP server, which in this case, will simply echo the request:

if response.ok:
    print(“Successfully uploaded the file”)
    print(response.text)
else:
    print(“Error in File upload”)

Use the Python command to run your script in the terminal:

python file_upload.py

Your results would look something like this:

request-submit

Use Python’s Requests Library for Multiple Files

We use lists, which is the main difference between using requests to upload many files and uploading a single file. Write the following code in a new file called file_upload.py.

import requests

url = “http://httpbin.org/file”

Now make a dictionary-like variable named test files that has a list of names and files:
files = {
    “file_1”: open(“file.txt”, “rb”),
    “file_2”: open(“file_2.txt”, “rb”),
    “file_3”: open(“file_3.txt”, “rb”)
}

Just like the previous one, the form fields’ names serve as the keys while the files’ sizes serve as the values.

You can send the request and inspect the answer once the list is ready:

response = requests.post(url, files = files)

if response.ok:
    print(“Successfully uploaded the file”)
    print(response.text)
else:
    print(“Error in File upload”)

Use the Python command to run this script:

python file_upload.py

You will see the following output. 

output

Use Python Flask

Flask is an easy method for Python file upload. First, you need an HTML form, as shown in the first example, and that form should post the file to a certain URL. 

You can get the name of the file from request.files[] object and finally save it to the desired location. To get a safe version, it is advised to use the secure filename() function.

In the Flask object’s configuration settings, it is possible to specify the default upload file path and the maximum file size that can be uploaded.

Set the upload folder’s location:

app.config[‘UPLOAD_FOLDER’] specifies the largest file size that can be uploaded (in bytes).

app.config[‘MAX CONTENT PATH’]

The code below uses the URL rule ‘/upload – file’ to use the upload () function to perform the upload procedure and the URL rule ‘/upload’ to display the file upload.html in the templates folder.

A file selector and a submit button may be found on the page “upload.html”.

<html>
  <body>
      <form action = “http://localhost:5000/uploader” method = “POST”
        enctype = “multipart/form-data”>
        <input type = “file” name = “file” />
        <input type = “submit”/>
      </form>  
  </body>
</html>

Here is the Python code you have to write in Flask application. 

from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)

@app.route(‘/upload’)
def upload_file():
  return render_template(‘upload.html’)
@app.route(‘/uploader’, methods = [‘GET’, ‘POST’])
def upload_file():
  if request.method == ‘POST’:
      f = request.files[‘file’]
      f.save(secure_filename(f.filename))
      return ‘file uploaded successfully’
if __name__ == ‘__main__’:
  app.run(debug = True)

Use Filestack API

file-upload

We may also use the Python SDK and the Filestack API to upload files using a Python program. To obtain this SDK, use the PIP command during installation.

pip install filestack-python

The Filestack SDK must be started with the Python program after installation. Then create a Client instance using the Filestack API key. You will assist by this Client with the demanding tasks in this software.

from filestack import Client
c = Client(“API’s Key”) #replace with API key
filelnk = c.upload(filepath = ‘/path/of/file.png’)
print(filelnk.url)

Conclusion

We saw five effective and easy ways to upload a file using Python. The first method is specifically employed in creating web applications, while the second is used in creating desktop or standalone applications. 

As the OS module is closer to the system, it’s the fastest method among these. However, Filestack is the easiest method to use among these five options. Hopefully, you learned a lot from this article. Enjoy coding! 

FAQs

What is file() in Python?

A file is a crucial piece of data kept on a computer.

How do you upload multiple files in Python?

Use eval() in comprehension to loop over the files in the requests post files parameter if you have several files in a Python list.

How do you automate upload in Python?

Python allows us to use Selenium to automate file uploading. The send keys method can be used to accomplish this.

How do I create an automatic file in Python?

We can create a new file using the open() function with the “w” argument.




Share

Related Post
error: Content is protected !!