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}`);
});