Learn how to build a file sharing app with v0. Follow our step-by-step guide

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Create two essential files: main.py and requirements.txt. Also, create a folder called "uploads" for storing uploaded files. This folder will be created by the app if it does not exist.
Since v0 does not have a terminal, include code in main.py that automatically checks and installs required dependencies. Insert the following code snippet at the very top of your main.py file. This snippet attempts to import Flask and installs it if it is not found.
try:
import flask
except ImportError:
import subprocess
subprocess.check\_call(["pip", "install", "Flask"])
import flask
In the main.py file, insert the following code immediately after the dependency installation snippet. This code sets up a basic file sharing app using Flask. It creates a web server that provides an HTML form for file uploads, saves files to the "uploads" folder, and displays a list of uploaded files with links to access them.
from flask import Flask, request, redirect, urlfor, sendfrom\_directory
import os
app = Flask(name)
// Define a folder to store uploaded files
upload\_folder = os.path.join(os.getcwd(), "uploads")
if not os.path.exists(upload\_folder):
os.makedirs(upload\_folder)
// Configure the app to use the uploads folder
app.config["UPLOADFOLDER"] = uploadfolder
// Create the homepage that shows an upload form and a list of available files
@app.route("/", methods=["GET"])
def index():
html\_form = """
File Sharing App
Upload a File
Files Available
"""
files = os.listdir(app.config["UPLOAD\_FOLDER"])
for file in files:
file\_link = "- {}
".format(file, file)
htmlform += filelink
html\_form += """
"""
return html\_form
// Handle file uploads by saving the uploaded file to the uploads folder
@app.route("/upload", methods=["POST"])
def upload\_file():
if "file" not in request.files:
return "No file part in the request."
file = request.files["file"]
if file.filename == "":
return "No file selected."
filepath = os.path.join(app.config["UPLOAD\_FOLDER"], file.filename)
file.save(filepath)
return redirect(url\_for("index"))
// Serve uploaded files so that they can be accessed via a link
@app.route("/files/", methods=["GET"])
def uploaded\_file(filename):
return sendfromdirectory(app.config["UPLOAD\_FOLDER"], filename)
// Entry point: run the application on host 0.0.0.0 and port 8080
if name == "main":
app.run(host="0.0.0.0", port=8080)
Create a new file named requirements.txt in your project root and add the following dependency so that v0 can manage and install Python packages automatically:
Flask
After making all the above changes, click the Run button in v0. The application starts, binds to host "0.0.0.0" and port 8080, and automatically creates the uploads folder if it does not exist.
When the app runs, a URL will be provided. Click the URL to open the file sharing interface in your browser. Use the upload form to select and upload a file. Once uploaded, the file will appear in the list with a link that you can click to access or download the file.
To add more features or improve security (for example, file deletion or more robust file type handling), update the code in main.py accordingly and click Run to redeploy the app. This modular structure lets you easily maintain and enhance your file sharing application with v0.
const express = require('express');
const multer = require('multer');
const mongoose = require('mongoose');
const crypto = require('crypto');
const app = express();
mongoose.connect('mongodb://localhost:27017/fileSharing', { useNewUrlParser: true, useUnifiedTopology: true });
const fileSchema = new mongoose.Schema({
filename: String,
fileHash: String,
uploadDate: { type: Date, default: Date.now },
chunks: [String]
});
const File = mongoose.model('File', fileSchema);
const storage = multer.memoryStorage();
const upload = multer({ storage });
// Upload endpoint: splits file into 1MB chunks and stores base64 encoded chunks in MongoDB.
app.post('/upload', upload.single('file'), async (req, res) => {
if (!req.file) return res.status(400).send('No file uploaded.');
const fileBuffer = req.file.buffer;
const md5sum = crypto.createHash('md5').update(fileBuffer).digest('hex');
const chunkSize = 1024 \* 1024; // 1MB
const totalChunks = Math.ceil(fileBuffer.length / chunkSize);
const chunks = [];
for (let i = 0; i < totalChunks; i++) {
const start = i \* chunkSize;
const end = Math.min(start + chunkSize, fileBuffer.length);
chunks.push(fileBuffer.slice(start, end).toString('base64'));
}
const file = new File({
filename: req.file.originalname,
fileHash: md5sum,
chunks
});
await file.save();
res.json({ message: 'File uploaded successfully.', fileId: file.\_id });
});
// Download endpoint: reconstructs the file from stored chunks.
app.get('/download/:id', async (req, res) => {
const file = await File.findById(req.params.id);
if (!file) return res.status(404).send('File not found.');
const fileBuffer = Buffer.concat(file.chunks.map(chunk => Buffer.from(chunk, 'base64')));
res.set('Content-Disposition', attachment; filename="${file.filename}");
res.send(fileBuffer);
});
app.listen(3000, () => console.log('Server running on port 3000'));
const express = require('express');
const AWS = require('aws-sdk');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
AWS.config.update({
accessKeyId: 'YOURAWSACCESS\_KEY',
secretAccessKey: 'YOURAWSSECRET\_KEY',
region: 'us-east-1'
});
const s3 = new AWS.S3();
app.post('/get-presigned-url', (req, res) => {
const { fileName, fileType } = req.body;
const s3Params = {
Bucket: 'YOURBUCKETNAME',
Key: uploads/${Date.now()}\_${fileName},
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, url) => {
if (err) {
console.error(err);
return res.status(500).json({ error: 'Error generating the presigned URL' });
}
res.json({
signedRequest: url,
url: }
});
});
});
app.listen(4000, () => console.log('Server running on port 4000'));
const express = require('express');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
const app = express();
const SECRETKEY = 'YOURSECRET\_KEY';
app.use(express.json());
app.post('/generate-download-token', (req, res) => {
const { fileId } = req.body;
const filePath = path.join(\_\_dirname, 'uploads', fileId);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
const token = jwt.sign({ fileId, filePath }, SECRET\_KEY, { expiresIn: '10m' });
res.json({ token });
});
app.get('/download', (req, res) => {
const token = req.query.token;
if (!token) return res.status(400).send('Token required.');
try {
const payload = jwt.verify(token, SECRET\_KEY);
fs.access(payload.filePath, fs.constants.R\_OK, (err) => {
if (err) return res.status(404).send('File not accessible.');
res.download(payload.filePath);
});
} catch (err) {
res.status(401).send('Invalid or expired token.');
}
});
app.listen(3001, () => console.log('Server running on port 3001'));

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
This guide explains the basic practices for building a file sharing application (version 0). The goal is to help you create an app where users can upload, download, and view files. You do not need advanced technical knowledge to follow these steps. The guide uses simple language and examples for clarity.
You need to set up a folder structure that holds all the code, uploaded files, and configuration files. This is how you can organize your project:
The folder structure may look like this:
project\_folder/
├── app.py
├── uploads/ // This folder will store user-uploaded files.
└── config.txt // A simple text file for configuration values.
You can pick a language that you are comfortable with. For beginners, Python with Flask is a popular choice. Alternatively, you can use JavaScript with Node.js and Express.
Below is an example command to install Flask:
pip install Flask
The file upload feature is an essential part of the file sharing app. This feature allows users to choose a file from their computer and send it to the server.
An example using Python with Flask is provided. In your main file ("app.py"), you can add the following code:
from flask import Flask, request, sendfromdirectory, redirect, urlfor, rendertemplate
import os
The line below creates an instance of the Flask class.
app = Flask(name)
Define the folder where uploaded files will be stored.
UPLOAD\_FOLDER = 'uploads'
app.config['UPLOADFOLDER'] = UPLOADFOLDER
Make sure the upload folder exists.
if not os.path.exists(UPLOAD\_FOLDER):
os.mkdir(UPLOAD\_FOLDER)
This route serves the main page with the upload form.
@app.route('/')
def index():
return '''
Upload your file
'''
This route handles the file upload submission.
@app.route('/upload', methods=['POST'])
def upload\_file():
# Access the uploaded file from the form.
file = request.files['file']
# Save the file in the UPLOAD\_FOLDER.
file.save(os.path.join(app.config['UPLOAD\_FOLDER'], file.filename))
# After saving, redirect the user to a page showing the list of available files.
return redirect(urlfor('fileslist'))
This route lists all uploaded files.
@app.route('/files')
def files\_list():
files = os.listdir(app.config['UPLOAD\_FOLDER'])
# Create a basic HTML list for the files.
files\_html = 'Uploaded Files
'
for f in files:
# Link each file to the download route.
files\_html += '- {}
'.format(f, f)
files\_html += '
'
return files\_html
This route handles file download.
@app.route('/download/')
def download\_file(filename):
# Serve the file from the UPLOAD\_FOLDER.
return sendfromdirectory(app.config['UPLOAD\_FOLDER'], filename)
if name == "main":
# The app will run on host 0.0.0.0 and port 5000 by default.
app.run(host="0.0.0.0", port=5000)
This code creates a simple web server that lets users upload files, list them, and download them. You can use this as the basic version (v0) of your file sharing app.
To keep your application safe and working nicely, you should validate what files users upload. This is important because you never know if a file might be too big or of a type that could be harmful.
An example snippet of how to check file extensions in Python is:
ALLOWED\_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
def allowed\_file(filename):
# This function checks if the file has a valid extension.
return '.' in filename and \\
filename.rsplit('.', 1)[1].lower() in ALLOWED\_EXTENSIONS
Modify the upload\_file route to check file validations.
@app.route('/upload', methods=['POST'])
def upload\_file():
file = request.files['file']
if file and allowed\_file(file.filename):
file.save(os.path.join(app.config['UPLOAD\_FOLDER'], file.filename))
return redirect(urlfor('fileslist'))
else:
return 'Invalid file type. Please choose a file with a valid extension.'
It is good practice to handle errors so that the app does not crash unexpectedly. Provide users with clear feedback if something goes wrong.
You may modify your upload route to incorporate more error handling as shown in the example above.
Before making your app public, test it thoroughly:
After testing, you may decide to deploy your file sharing app so that others can access it. For a basic deployment:
When deploying, update your configuration to reflect production settings (for example, different ports and security configurations).
This guide covered the foundational best practices for building a file sharing app (v0). You learned how to:
As you gain more experience, you can add more detailed features such as user authentication, advanced security scans, and more robust error handling. This version provides a simple and clear starting point for your file sharing application.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. Duis cursus, mi quis viverra ornare, eros dolor interdum nulla, ut commodo diam libero vitae erat. Aenean faucibus nibh et justo cursus id rutrum lorem imperdiet. Nunc ut sem vitae risus tristique posuere.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
Unordered list
Bold text
Emphasis
Superscript
Subscript
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
Unordered list
Bold text
Emphasis
Superscript
Subscript
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
Unordered list
Bold text
Emphasis
Superscript
Subscript
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
Unordered list
Bold text
Emphasis
Superscript
Subscript

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
Unordered list
Bold text
Emphasis
Superscript
Subscript
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.