Sunday, January 5, 2025

Use webpage to upload and download files

In the current code, uploaded files are not actually stored on a server. The files are just read and stored temporarily in the browser’s memory using JavaScript FileReader and Blob objects. These files are not uploaded to any server or remote storage, and are instead stored locally in the browser for temporary use.

How the file storage works:
When the user selects a file, it is read into an ArrayBuffer, then converted into a URL using Blob.
This temporary URL is saved in the browser’s memory using a Map object for easy access to the files.
When the user clicks the “Download” button, the file is downloaded using this temporary URL.
However, the file is not saved to any server, meaning if the page is refreshed, the uploaded files will be lost. If you want to save uploaded files on a server and provide download links, you’ll need to implement server-side storage.

Code Functionality:
This code implements a simple webpage file upload download and refresh functionality:

The user can select multiple files to upload, but the files are only stored in the browser’s memory and not uploaded to a server.
The uploaded files are displayed on the page, and users can download these files.
There is a “Refresh Page” button on the page that, when clicked, reloads the entire page and resets the file list.
Code Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Transfer Tool</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
    #fileList { margin-top: 20px; }
    button { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>File Transfer Tool</h1>
  <p>Upload and download files using this page.</p>
  
  <!-- File Upload Section -->
  <input type="file" id="fileInput" multiple>
  <button id="uploadBtn">Upload Files</button>
  
  <!-- Refresh Button -->
  <button id="refreshBtn">Refresh Page</button>

  <!-- File List -->
  <div id="fileList">
    <h3>Uploaded Files</h3>
    <ul id="files"></ul>
  </div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const refreshBtn = document.getElementById('refreshBtn');
    const fileList = document.getElementById('files');

    // Store uploaded files in memory
    const uploadedFiles = new Map();

    // File upload functionality
    uploadBtn.addEventListener('click', () => {
      const files = fileInput.files;
      if (files.length === 0) {
        alert('Please select files!');
        return;
      }

      // Store files in memory
      Array.from(files).forEach((file) => {
        const fileURL = URL.createObjectURL(file);  // Create a temporary URL
        uploadedFiles.set(file.name, { file, fileURL });
      });

      alert('Files uploaded successfully');
      // Update the file list
      updateFileList();
    });

    // Update the file list
    function updateFileList() {
      fileList.innerHTML = '';  // Clear the list
      uploadedFiles.forEach((fileData, fileName) => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
          <span>${fileName}</span>
          <a href="${fileData.fileURL}" download="${fileName}" style="margin-left: 10px;">Download</a>
        `;
        fileList.appendChild(listItem);
      });
    }

    // Refresh page functionality
    refreshBtn.addEventListener('click', () => {
      location.reload();  // Reload the entire page
    });
  </script>
</body>
</html>

Code Explanation:
File Upload Functionality:

When the user clicks the “Upload Files” button, the selected files are given a temporary URL using URL.createObjectURL() and stored in the browser’s memory.
The uploaded files will be displayed on the page by calling updateFileList().
File List Update:

After uploading files, the updateFileList() function is called to refresh the file list on the page. Files are shown with their names and a download link.
Refresh Page:

When the “Refresh Page” button is clicked, location.reload() is called to reload the entire page, simulating a browser refresh. This clears the file list and resets the page content.
—————–
How to upload files to a server
To ensure that uploaded files are stored on the server and can be downloaded, you would need both front-end and back-end implementation:

Frontend: Use the FormData object to send the file to the server.
Backend: The server will receive the file and store it at a designated location.
Example: File upload using Node.js backend
1. Frontend: Uploading files to the server
Here’s an updated version of the front-end code to handle file uploads to the server.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Transfer Tool</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
    #fileList { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>File Transfer Tool</h1>
  <p>Use this page to upload and download files.</p>
  
  <!-- File upload section -->
  <input type="file" id="fileInput" multiple>
  <button id="uploadBtn">Upload File</button>

  <!-- File list -->
  <div id="fileList">
    <h3>Uploaded Files</h3>
    <ul id="files"></ul>
  </div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const fileList = document.getElementById('files');

    // File upload functionality
    uploadBtn.addEventListener('click', () => {
      const files = fileInput.files;
      if (files.length === 0) {
        alert('Please select a file!');
        return;
      }

      const formData = new FormData();
      for (const file of files) {
        formData.append('files', file);  // Add the file to the FormData object
      }

      // Send the file to the server
      fetch('/upload', {
        method: 'POST',
        body: formData,
      })
      .then(response => response.json())
      .then(data => {
        alert('File uploaded successfully');
        // Update file list (show file paths or information returned from server)
        updateFileList(data.files);
      })
      .catch(error => {
        console.error('File upload failed:', error);
        alert('File upload failed');
      });
    });

    // Update file list
    function updateFileList(files) {
      fileList.innerHTML = '';
      files.forEach(file => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
          <span>${file.name}</span>
          <a href="${file.url}" download="${file.name}" style="margin-left: 10px;">Download</a>
        `;
        fileList.appendChild(listItem);
      });
    }
  </script>
</body>
</html>

2. Backend: Using Node.js to handle file storage
You can use Node.js with Express and the Multer library to handle the file upload and storage on the server.

First, install the necessary packages:

npm install express multer

Then, set up the Node.js server:

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();

// Configure storage settings for uploaded files
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');  // Folder where the files will be stored
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));  // Filename format
  }
});

const upload = multer({ storage: storage });

// File upload route
app.post('/upload', upload.array('files'), (req, res) => {
  const files = req.files.map(file => ({
    name: file.originalname,
    url: `http://localhost:3000/uploads/${file.filename}`,  // URL to access the file
  }));

  res.json({ files });  // Return file information to the frontend
});

// Serve static files (uploaded files)
app.use('/uploads', express.static('uploads'));

// Start the server
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Explanation:
Frontend: Sends the file to the server using FormData. Upon successful upload, the server returns the file information (name and URL), which is then displayed on the webpage.
Backend: The multer library handles file uploads, stores the files in the uploads/ folder, and generates a URL to access each uploaded file.
How to Test:
1.Start the Node.js server.
2.Open the HTML page and upload a file.
3.Once the file is uploaded, it will be stored on the server in the uploads/ directory, and you can download it by clicking the download link.
This method will actually store the uploaded files on the server, allowing them to be accessed and downloaded by the user.

Add comment

Fill out the form below to add your own comments