0

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 prompt the user to download the image in their local browser. 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.

Ruok2bu
  • 13
  • 3
  • 1
    That's client code, right? You can't save something on a server unless you're running code on the server. Am I reading it wrong? – Tim Roberts Jul 29 '23 at 04:53
  • You are maybe looking for this https://stackoverflow.com/questions/10673122/how-to-save-canvas-as-an-image-with-canvas-todataurl . But like said before, you can save your image locally (i.e. on client side) but if you want to upload it to a server app that s different. Your question is a little confusing regarding to this. – Peterrabbit Jul 29 '23 at 07:12

2 Answers2

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}`);
});
Asiri Hewage
  • 577
  • 3
  • 16
-1

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.

Bita
  • 14
  • 3
  • 1
    This is node.js code but the question is about js browser code so this wouldn't work. (Also it wouldn t be appropriate to save an image in a text file) – Peterrabbit Jul 29 '23 at 08:55