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.

Saturday, January 4, 2025

How to Check if Sleep Mode is Enabled on Windows 11 Using Command Line

You can use the powercfg command to check the status of sleep mode in Windows 11. Here’s how:

Steps to Check Sleep Mode Status
1.Open Command Prompt as Administrator

Press Win + S, search for Command Prompt.
Right-click on Command Prompt and select Run as administrator.
2.View Power Plan and Sleep Settings Run the following command to view the detailed power plan settings, including sleep mode:

powercfg /query

This will display all current settings, including the timeout for sleep mode under both plugged-in and battery conditions.

3.Check Specific Sleep Timeout To check the specific sleep timeout values:

For sleep timeout on AC power:

powercfg -query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE

For sleep timeout on battery power:

powercfg -query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE

4.Check Hibernate (Standby) Mode Use the following command to see if hibernation is enabled and supported on your system:

powercfg /a
or
powercfg -a

This will list the available power states, including Standby (S3) and Hibernate, if enabled.

Example Output
Example 1: Output for powercfg /query

Power Setting GUID: SUB_SLEEP
Power Setting Name: Sleep idle timeout (AC)
Possible Settings: ...
Current AC Power Setting Index: 30 (minutes)

Example 2: Output for powercfg /a

The following sleep states are available on this system:
    Standby (S3)
    Hibernate

Summary
Sleep Mode Timeout: Use powercfg -query to check sleep mode timeout settings.
Hibernate Mode: Use powercfg /a to verify if hibernation is enabled.
Adjust Settings: If necessary, modify sleep settings using powercfg -change.

How to Disable Sleep and Standby Modes on Windows 11 Using Command Line

Here’s how you can turn off sleep and standby modes using the PowerCfg command on Windows 11:

Steps:
1. Open Command Prompt (Run as Administrator)
Press Win + S and search for “cmd”.
Right-click on “Command Prompt” and select Run as administrator.
2. Disable Sleep Mode
Run the following commands to disable sleep mode:

powercfg -change -standby-timeout-ac 0
powercfg -change -standby-timeout-dc 0

-standby-timeout-ac: Disables sleep mode when plugged into AC power.
-standby-timeout-dc: Disables sleep mode when on battery power.
0: Sets the timeout to 0, effectively disabling sleep mode.
3. Disable Hibernate (Standby) Mode
Run the following command to turn off hibernation:

powercfg -hibernate off

Restore Settings (Optional)
To re-enable sleep or standby modes, use these commands:

To enable sleep mode (e.g., set to 30 minutes):

powercfg -change -standby-timeout-ac 30
powercfg -change -standby-timeout-dc 30

To enable hibernation:

powercfg -hibernate on

Verify the Settings
Run this command to view the current power plan settings:

powercfg /query

Check if the changes have been applied successfully.

With these steps, you can manage sleep and standby modes on your Windows 11 system easily.