skip to Main Content

I have a script that’s broken and its currently trying to upload form contents to imgbb. I dont want that, instead i want it to save the form contents to a file locally on the webserver. How do i do this? Here’s the current code:

const formData = new FormData();
            formData.append("image", canvas.toDataURL().split(',')[1])
            var req = new XMLHttpRequest()
            req.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    response = JSON.parse(this.response)
                    console.log(response)
                    url = response.data.image.url
                    $('#Loading').hide();
                    $('#URL').val(url).fadeIn();
                }
            }
            req.open("POST", 'https://api.imgbb.com/1/upload?key=xxxxxxxxxxxxxxxxxxxxxxxxxx', true)
            req.send(formData)

        },

Ive tried the tutorial at https://www.tutorialspoint.com/how-to-create-and-save-text-file-in-javascript but it doesnt work.

2

Answers


  1. Here you are sending a POST request with the image to the API you mentioned in the question. If you want to save it inside your web server directory, you can modify the code like this.

    Client Side Code

    // Assuming canvas and other elements are properly defined
    function saveFileLocally() {
      const formData = new FormData();
      formData.append("image", canvas.toDataURL().split(',')[1]);
    
      var req = new XMLHttpRequest();
      req.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          response = JSON.parse(this.response);
          console.log(response);
          // Handle the response from the server, if needed
        }
      };
      req.open("POST", "/upload", true); // Replace "/upload" with your server-side endpoint URL
      req.send(formData);
    }
    

    Server Side Code

    const express = require('express');
    const multer = require('multer'); // For handling file uploads
    const fs = require('fs'); // For file system operations
    const app = express();
    
    // Set up multer for file upload (you can configure the destination folder and other options)
    const upload = multer({ dest: 'uploads/' });
    
    // POST endpoint to handle file upload
    app.post('/upload', upload.single('image'), (req, res) => {
      // Assuming 'image' is the name attribute of the file input on the client-side
      const imageFile = req.file;
    
      // If the file was successfully uploaded
      if (imageFile) {
        // Read the contents of the uploaded file
        fs.readFile(imageFile.path, (err, data) => {
          if (err) {
            console.error('Error reading the uploaded file:', err);
            res.status(500).json({ error: 'Failed to read the uploaded file.' });
          } else {
            // Save the file locally on the server (you can specify a different path if needed)
            const destinationPath = `uploads/${imageFile.originalname}`;
            fs.writeFile(destinationPath, data, (err) => {
              if (err) {
                console.error('Error saving the file:', err);
                res.status(500).json({ error: 'Failed to save the file.' });
              } else {
                // File was saved successfully
                res.json({ message: 'File uploaded and saved successfully.' });
              }
            });
          }
        });
      } else {
        res.status(400).json({ error: 'No file was uploaded.' });
      }
    });
    
    // Start the server
    const port = 3000; // Replace with your desired port number
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });
    
    Login or Signup to reply.
  2. To save the form contents to a file locally on the webserver instead of uploading them to imgbb, you can modify the script as follows:

    const fs = require('fs');
    const data = canvas.toDataURL().split(',')[1];
    fs.writeFile('formContents.txt', data, (err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });

    This script uses the fs module to write the form contents to a file named formContents.txt on the webserver. The writeFile method takes three arguments: the name of the file, the data to be written, and a callback function that is called when the operation is complete. In this case, the callback function logs a message to the console indicating that the file has been saved.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search