Learn how to upload files to an ML backend via a web form. Follow our step-by-step guide for a quick, secure integration.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
post and the encoding type (enctype) is multipart/form-data, which is essential for sending file data.<input type="file"> element for file selection. Optionally, add other input elements for extra parameters if your machine learning (ML) model requires them.
// Example HTML form
request.files in Flask).
// Example using Python Flask
from flask import Flask, request, jsonify
from werkzeug.utils import secure\_filename
app = Flask(**name**)
// Define allowed file extensions for security
ALLOWED\_EXTENSIONS = {'jpg', 'png', 'csv'}
def allowed\_file(filename):
// Check if the file's extension is allowed
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED\_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload\_file():
// Verify that the request contains a file part
if 'data\_file' not in request.files:
return jsonify({'error': 'No file uploaded'}), 400
file = request.files['data\_file']
// If no file is selected, return an error
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
if file and allowed\_file(file.filename):
// Sanitize the file name to prevent path traversal attacks
filename = secure\_filename(file.filename)
// Optionally save the file to disk if necessary
filepath = "./uploads/" + filename
file.save(filepath)
// Process the file and integrate with the ML model below
result = process\_file(filepath)
return jsonify({'result': result}), 200
else:
return jsonify({'error': 'File type not supported'}), 400
// Dummy function that simulates file processing and ML inference
def process\_file(filepath):
// Load the file (image, CSV, etc.) and preprocess as required by your ML model
// For example: resizing an image, normalizing data, parsing CSV values
// Load your ML model (using a library such as TensorFlow, PyTorch, or scikit-learn)
// Perform inference/prediction on the processed data
// Here, we simply return a dummy response
return "Processed file " + filepath
if **name** == '**main**':
app.run(debug=True)
torch.load, or any other format.
// Expanding the process\_file function for ML integration
import numpy as np
// Uncomment and adjust the following imports based on your ML framework
// import tensorflow as tf
// import torch
def process\_file(filepath):
// Example case: process an image file for a TensorFlow model
from PIL import Image
// Open and preprocess the image
image = Image.open(filepath)
image = image.resize((224, 224)) // Resize image to expected dimensions
image\_array = np.array(image) / 255.0 // Normalize pixel values to [0,1]
image_array = np.expand_dims(image\_array, axis=0) // Add batch dimension
// Load your pre-trained ML model (using TensorFlow as an example)
// model = tf.keras.models.load_model('path_to_your_model')
// prediction = model.predict(image\_array)
// For demonstration, we simulate a prediction result
prediction = "simulated prediction value"
return "Inference result: " + str(prediction)
fetch API or XMLHttpRequest to asynchronously upload the file and handle responses dynamically.
// Example of AJAX file upload using JavaScript
document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form from submitting the traditional way
var formData = new FormData(this);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
// Display the ML model inference result or error message
alert("Server response: " + JSON.stringify(data));
})
.catch(error => {
console.error('Error during file upload:', error);
});
});
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â