Here's an example of how you can create an HTML form to upload an audio file and a Python script using the Flask framework to handle the file upload via an API endpoint:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload():
if 'audio_file' not in request.files:
return 'No audio file found', 400
audio_file = request.files['audio_file']
if audio_file.filename == '':
return 'No selected file', 400
# Save the uploaded audio file
audio_file.save('uploads/' + audio_file.filename)
return 'Audio file uploaded successfully', 200
if __name__ == '__main__':
app.run()
Explanation:
The HTML form (upload.html) contains an input field of type "file" with the name "audio_file". The accept attribute is set to "audio/*" to restrict the file selection to audio files only. The form's action attribute specifies the API endpoint ("/upload") to handle the file upload, and the method attribute is set to "POST". The enctype attribute is set to "multipart/form-data" to allow file uploads.
In the Python script (app.py), we create a Flask application instance.
The index() route renders the HTML form template (upload.html) when accessed.
The upload() route handles the file upload when the form is submitted. It checks if the "audio_file" field exists in the request files. If not, it returns an error message with a 400 status code.
If the "audio_file" field exists, we retrieve the uploaded file using request.files['audio_file'].
We check if the filename is empty. If it is, we return an error message with a 400 status code.
If the filename is not empty, we save the uploaded audio file to the "uploads" directory using audio_file.save(). Make sure to create an "uploads" directory in the same location as the Python script.
Finally, we return a success message with a 200 status code.
The if __name__ == '__main__': block runs the Flask application when the script is executed directly.
To run this code, make sure you have Flask installed (pip install flask). Place the HTML file (upload.html) in a "templates" directory and create an "uploads" directory in the same location as the Python script. Then, run the Python script and access the form by navigating to http://localhost:5000 in your web browser.