javascript 保存成jpg而不是上传到imgbb?

hxzsmxv2  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(111)

我有一个脚本,它的破碎,目前正试图上传形式的内容到imgbb。我不想这样,相反,我希望它保存的形式内容到一个文件本地的Web服务器上提示用户下载图像在他们的本地浏览器。我该怎么做?下面是当前代码:

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)

        },

字符串
我在https://www.tutorialspoint.com/how-to-create-and-save-text-file-in-javascript上试过这个教程,但它不起作用。

6gpjuf90

6gpjuf901#

在这里,您正在向问题中提到的API发送带有图像的POST请求。如果你想把它保存在你的web服务器目录中,你可以这样修改代码。
客户端代码

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

字符串
服务器端代码

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

t3psigkw

t3psigkw2#

要将表单内容保存到Web服务器上的本地文件中,而不是将其上传到imgbb,您可以按如下方式修改脚本:

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!');
});

字符串
此脚本使用fs模块将表单内容写入Web服务器上名为formContents.txt的文件。writeFile方法有三个参数:文件名、要写入的数据以及操作完成时调用的回调函数。在这种情况下,回调函数会向控制台记录一条消息,指示文件已保存。

相关问题