Flask-API Library Implementation File Upload and Download Functional Practical Guide
# FLASK-API library to implement a practical guide to upload and download function
Flask-API is a library for building a web API, which is based on the Flask framework of Python.This guide will show you how to use the Flask-API library to implement the file upload and download function.
## 1. Configuration environment
First, make sure that your system has installed Python and Flask-API libraries.You can use the following command to install the Flask-API library in the command line:
pip install Flask-API
## 2. Create FLASK application
First of all, we need to create a Flask application to process file upload and download requests.Create a Python script in your project directory, such as `app.py`, and add the following code:
python
from flask_api import FlaskAPI
app = FlaskAPI(__name__)
if __name__ == "__main__":
app.run(debug=True)
The above code creates a Flask application and starts a local server.You can use the parameters of the `app.run () method to configure, such as setting the host and port number.
## 3. Implement file upload
Next, we will implement the function of file uploading.In order to process file upload requests, we will create a route in Flask applications, which will process the `Post` request and save uploaded files.
Add the following code to process the file upload.Add the following code to the `app.py` file:
python
from flask import request
from werkzeug.utils import secure_filename
import os
Upload_folder = 'UPLOADS' # define the directory of the upload file preservation
Allowed_extEnsions = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} #
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return {'error': 'No file part'}, 400
file = request.files['file']
if file.filename == '':
return {'error': 'No file selected'}, 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return {'message': 'File uploaded successfully'}, 201
else:
return {'error': 'File type not allowed'}, 400
In the above code, we first define the directory uploaded by a file `upload_folder`, and set the type of file that allows uploading.Then, we handle the logic of file uploading in the function of the `UPLOAD_FILE ()` function.We first check whether the request contains files, and then check whether the type of file is allowed to upload.If everything is normal, we use the method of `secure_filename () to save the file and return a message to be successfully uploaded.
## 4. Implement file download
Now, let's see how to achieve the function of file download.We will create another routing in Flask applications, which will process the `Get` request and return the request file.
Add the following code to process the file download.Add the following code to the `app.py` file:
python
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
return flask.send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
else:
return {'error': 'File not found'}, 404
In the above code, we define the route of the processing file download request `/download/<filename>`.We first check whether the requested file is existed in the upload directory and uses the method to return the file to the user with the method of `Flask.SEND_FROM_DIRECTORY ()`.
## 5. Run application
Now, we have implemented the function of file uploading and downloading, which can run FLASK applications.
In the command line, enter your project directory and run the following command to start the application:
python app.py
This will start a local server to monitor the default `5000` port.You can test the file upload and download function by accessing the following URL:
-File upload: `http:// localhost: 5000/upload`
-File download: `http:// localhost: 5000/download/filename`
Make sure to replace the `localhost: 5000` with your server host and port number.
## 6. Example front -end code
The following is an example of a simple HTML and JavaScript code. It is used to upload and download files through AJAX requests:
html
<!DOCTYPE html>
<html>
<head>
<title>File Upload and Download Example</title>
</head>
<body>
<h1>File Upload and Download Example</h1>
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>
<br>
<a href="#" id="downloadLink" style="display:none;">Download</a>
<script>
function uploadFile() {
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:5000/upload', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201) {
document.getElementById('downloadLink').style.display = 'block';
document.getElementById('downloadLink').setAttribute('href', 'http://localhost:5000/download/' + file.name);
}
};
xhr.send(formData);
}
</script>
</body>
</html>
In the above code, we created a simple HTML page, which contains an input box for selecting files and a button for uploading files.After the uploaded file was successful, we set up a download link through Ajax request.
This is just a sample front -end code, you can modify it according to your own needs.
## Summarize
Through the Flask-API library, you can easily implement the file upload and download function.This guide introduces the routing of how to embed the file upload and download, and provide an example of the HTML page for testing.
Remember to conduct appropriate security verification and error treatment in practical applications.