0% found this document useful (0 votes)
7 views21 pages

Slot12_Upload-Download-Files

The document provides an overview of file upload and download processes, specifically focusing on implementations in Node.js and React. It includes detailed instructions and code examples for uploading single and multiple files using Multer, as well as downloading files from a server. Additionally, it outlines the necessary setup for creating a server and handling file operations effectively.

Uploaded by

aeskychung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

Slot12_Upload-Download-Files

The document provides an overview of file upload and download processes, specifically focusing on implementations in Node.js and React. It includes detailed instructions and code examples for uploading single and multiple files using Multer, as well as downloading files from a server. Additionally, it outlines the necessary setup for creating a server and handling file operations effectively.

Uploaded by

aeskychung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Upload & Download Files

Objectives
◆ Introduction Upload
◆ Demo Upload with Single Upload and Multiple Upload
◆ Introduction and Demo Download

2
What is Upload?

• It is the process of sending data from a personal computer to a


server or an online platform.
• For example, when you post a photo on social media or
upload a file to Google Drive, you are performing an upload.

3
Uploading Large Files in Node.js

• Uploading large files in Node.js can be challenging due to


limitations in file size and server memory.
• However, there are several advanced techniques that can be
used to efficiently upload large files in Node.js.
• Some of the best practices for uploading large files:
• Using Multer *
• Using Amazon S3
• Using a CDN

4
Using Multer

• Multer - middleware for handling multipart/form-data (used for


file upload forms).
• Install package: npm install multer

5
Demo 1: Using Multer with
Single File
• 1. Create a simple server to handle uploads: To support file
upload processing in a Node.js application using Express, a
specific route needs to be set up.
• Here's how to set up the uploadRoutes.js file to handle file
upload requests:
• Set up a router using express and multer, specialized middleware for
handling multipart/form-data, which is the data type commonly used
for file uploads.
• Create the corresponding folder: uploads

7
// routers/uploadRoutes.js
const express = require('express');
const multer = require('multer');
const router = express.Router();

• multer.diskStorage: // 1. Configure the storage location and file name

Configure where to save files const storage = multer.diskStorage({

and file name format saved


destination: function (req, file, cb) {
cb(null, 'uploads/’);

on the server. // 2. Make sure you have created this folder in your project
},

destination: Function to
filename: function (req, file, cb) {
• cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop());
determine where to save the }

uploaded file.
});

filename: Function to
const upload = multer({ storage: storage });

determine the file name when // 3. Route to handle POST request for file upload

saved on the server.


router.post('/upload', upload.single('file'), function (req, res, next) {
if (!req.file) {
return res.status(400).send('No files were uploaded.');
• upload.single('file'): Multer }

middleware processes a file


res.send('File ' + req.file.originalname + ' uploaded successfully');
});
uploaded with name="file" in
form data.
module.exports = router;

8
const express = require('express');
const uploadRoutes = require('./routes/uploadRoutes');
const app = express();

const cors = require('cors');


// CORS options if you want to customize them

• 1. Create a simple server const corsOptions = {


origin: 'http://localhost:3000’,

to handle uploads – cont’d: // or use '*' to allow all origins


optionsSuccessStatus: 200

Use router in server.js // some legacy browsers (IE11, various SmartTVs) choke on 204
};

After you have defined


app.use(cors(corsOptions));
• // Middlewares

uploadRoutes, you need to


app.use(express.json());
app.use(express.urlencoded({ extended: true }));

include this router in your // Routes


main application. app.use('/api', uploadRoutes);
// Static files
app.use(express.static('public'));

app.listen(8000, () => {
console.log('The server is running on port 8000');
});

9
import React, { useState } from 'react';
import axios from 'axios';
function FileUpload() {
const [file, setFile] = useState(null);
// Function to handle when file is selected
const onFileChange = event => {setFile(event.target.files[0]); };
// Function to handle when the user presses the "Upload" button
const onFileUpload = () => {
• 2. In React UI const formData = new FormData();
formData.append(

Next, React will send


"file",
• file,
a request to the file.name
); // Add files to the FormData object
/api/upload endpoint // Send FormData to the '/upload' endpoint on the server
axios.post("http://localhost:8000/api/upload", formData).then(response => {
to upload the file. console.log('File is uploaded successfully', response);
alert('File is uploaded successfully');
• This endpoint has }).catch(err => {
console.error('Error uploading file', err);alert('Error uploading file');
been defined in the });

Express server's
};
return (

uploadRoutes.js file <div>


<h1>File Upload</h1>
<input type="file" onChange={onFileChange} />
<button onClick={onFileUpload}>
Upload!
</button>
</div>
);
}
export default FileUpload;

10
• 2. In React UI – cont’d import FileUpload from "./Components/FileUpload";

function App() {
return (
<div className="App">
<header className="App-header">
<FileUpload />
</header>
</div>
);
}

export default App;

11
Demo 2: Using Multer with
Multiple File
// routers/uploadMultipeRoutes.js
const express = require('express');
const multer = require('multer');
const router = express.Router();

// 1. Configure the storage location and file name


const storage = multer.diskStorage({

In Server:
destination: function (req, file, cb) {
• },
cb(null, 'uploads/');

• To handle uploading multiple filename: function (req, file, cb) {

files at once, you will need to


cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop());
}
use Multer's upload.array or });

upload.fields method instead const upload = multer({ storage: storage });

of upload.single. // 2. Route to handle POST request for multiple file uploads

• Here's how you can modify the router.post('/upload', upload.array('files', 5), function (req, res, next) { // Replace
'file' with 'files' and limit the number to 5
code in if (!req.files || req.files.length === 0) {

uploadMultipleRoutes.js to
return res.status(400).send('No files were uploaded.');
}
handle uploading multiple // Get the list of uploaded files
files: const uploadedFiles = req.files.map(file => file.originalname);

res.send('Files ' + uploadedFiles.join(', ') + ' uploaded successfully');


});
const downloadRoutes =
require('./routes/downloadRoutes'); module.exports = router;

// Using downloadRoutes
app.use('/api', downloadRoutes);

13
// Components/FileUploadMultiple.js
import React, { useState } from 'react';
import axios from 'axios';
function FileUpload() {
const [files, setFiles] = useState([]);
// Function to handle when files are selected
const onFileChange = event => {
setFiles(event.target.files); // Let state be an array of files

In React UI:
};


// Function to handle when the user presses the "Upload" button
const onFileUpload = () => {

To allow multiple file


const formData = new FormData();
• // Add all files to the FormData object

uploads, you need


for (let i = 0; i < files.length; i++) {
formData.append(

to change the way


"files", // The field name must correspond to the name used in the backend
files[i],

you handle file state


files[i].name
);

and FormData
}
// Send FormData to the '/upload' endpoint on the server
axios.post("http://localhost:8000/api/upload", formData, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(response => {
alert('Files are uploaded successfully');
}).catch(err => { console.error('Error uploading files', err); });
};
return (
<div>
<h1>File Upload</h1>
<input type="file" multiple onChange={onFileChange} />
<button onClick={onFileUpload}>
Upload!
</button>
</div>
);
}
export default FileUpload;
14
• Demo: import FileUploadMultiple from "./Components/FileUploadMultiple";

function App() {
return (
<div className="App">
<header className="App-header">
<FileUploadMultiple />
</header>
</div>
);
}

export default App;

15
What is Download?

• It is the process of receiving data from the Internet or a server


to your computer or device.
• For example, when you download an app from the App Store
or save a file from email to your computer, you are performing
a download.

16
Demo 3: Download File
// routers/fileRoutes.js

• Create an API endpoint on the const express = require('express');


const router = express.Router();
Node.js server to list all files in const fs = require('fs');
const path = require('path');
the Upload folder. // Route to handle file list

router.get('/files', (req, res) => {


const fileRoutes = require('./routes/fileRoutes’); const uploadsDir = path.join(__dirname, '../uploads');

// Using fileRoutes fs.readdir(uploadsDir, (err, files) => {


app.use('/api', fileRoutes); if (err) {
console.log(err);
return res.status(500).send('Unable to scan directory: ' +
err);
}

res.json(files);
});
});

module.exports = router;

18
// FileList.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import DownloadFile from './DownloadFile';

function FileList() {
const [files, setFiles] = useState([]);

• Send a request from the useEffect(() => {

React app to this API


axios.get('http://localhost:8000/api/files')
.then(response => {

endpoint and display the


setFiles(response.data);
})
.catch(error => {
results. });
console.error('Error fetching files', error);

}, []);

return (
<div>
<h2>Uploaded Files</h2>
<ul>
{files.map((file, index) => (
<li key={index}>
{file} <DownloadFile filename={file} />
</li>
))}
</ul>
</div>
);
}

export default FileList;

19
import FileList from "./Components/FileList";

function App() {

return (
<div className="App">
<header className="App-header">
<FileList />
</header>
</div>
);
}

export default App;

20
Summary
◆ Concepts were introduced:
◆ Introduction Upload
◆ Demo Upload with Single Upload and Multiple Upload
◆ Introduction and Demo Download

21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy