Nodejs 图片上传问题

Nodejs 图片上传问题

刚开始学nodejs
前辈在服务器上写好了上传图片的demo 用的formidable form.parse 来接收数据 我在本地用request的请求过去 将图片获取到后 用fs.createReadStream() 读成文件流 想传过去 应该怎么写? 我用 form.append(“file”,fs.createReadStream()); 传过去的时会报错

TypeError: Object function (form) {
  if (form) {
    this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8')
    this.body = (typeof form === 'string') ? form.toString('utf8') : qs.stringify(form).toString('utf8')
    return this
  }
  // create form-data object
  this._form = new FormData()
  return this._form
} has no method 'append'

我想问问这里应该怎么写 才能实现上传图片


3 回复

针对你的问题,你在尝试使用 formidablerequest 进行图片上传时遇到了一些问题。你提到的错误是因为 formidableform.parse() 方法并不直接支持通过 form.append() 方法添加文件流。你需要确保正确地处理文件流,并将其传递给 formidable 处理。

示例代码

首先,确保你已经安装了所需的依赖库:

npm install formidable request

接下来,你可以按照以下步骤来实现图片上传功能:

服务器端代码(使用 formidable 接收图片)

const http = require('http');
const formidable = require('formidable');

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();
    
    form.parse(req, (err, fields, files) => {
      if (err) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('Bad Request');
        return;
      }

      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`File uploaded successfully!`);
    });

    form.on('fileBegin', (name, file) => {
      // 文件上传前的操作,例如更改文件名
      file.path = `${__dirname}/uploads/${file.name}`;
    });

    form.on('file', (name, file) => {
      console.log(`Uploaded ${file.name}`);
    });

  } else {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`
      <form action="/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="upload" multiple />
        <input type="submit" value="Upload" />
      </form>
    `);
  }
}).listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

客户端代码(使用 request 发送图片)

const request = require('request');
const fs = require('fs');

const formData = {
  upload: fs.createReadStream('/path/to/your/image.jpg')
};

request.post({ url: 'http://localhost:3000/upload', formData }, (err, response, body) => {
  if (err) {
    console.error('Error:', err);
  } else {
    console.log('Response:', body);
  }
});

解释

  1. 服务器端:我们使用 formidable 来解析上传的数据。form.parse() 方法用于解析来自客户端的表单数据。我们监听 fileBeginfile 事件来处理文件的上传过程。
  2. 客户端:使用 request 库发送 POST 请求,并通过 formData 对象将文件流附加到请求中。fs.createReadStream() 创建了一个可读流,该流被传递给 formData 对象中的 upload 键。

这样,你就可以通过客户端发送图片文件,并在服务器端成功接收到并保存该文件。


按着报错的意思… 楼主至少先改一下

根据你的描述,你在使用 request 发送图片并尝试将其通过 formidable 接收。这里有一些可能的问题:

  1. 你需要确保在创建 FormData 实例时,正确传递文件路径。
  2. 在发送请求时,需要正确设置 Content-Type 和其他相关头信息。

以下是一个简单的示例,展示如何使用 request 发送图片,并通过 formidable 在服务器端接收:

客户端代码(发送图片)

const request = require('request');
const fs = require('fs');

const formData = {
  file: fs.createReadStream('/path/to/your/image.jpg'),
};

request.post(
  { url: 'http://yourserver.com/upload',
    formData: formData
  },
  function optionalCallback(err, httpResponse, body) {
    if (err) {
      console.error('Upload failed:', err);
    } else {
      console.log('Upload successful!');
    }
});

服务器端代码(接收图片)

首先,确保你安装了 formidable

npm install formidable

然后,在你的服务器端处理上传的代码如下:

const formidable = require('formidable');
const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error('Error parsing form:', err);
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('Bad Request');
        return;
      }

      const oldPath = files.file.path;
      const newPath = __dirname + '/' + files.file.name;

      fs.rename(oldPath, newPath, (err) => {
        if (err) {
          console.error('Error moving file:', err);
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Internal Server Error');
          return;
        }

        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('File uploaded successfully');
      });
    });

    return;
  }

  // Handle other routes
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<html><body>Hello, World!</body></html>');
}).listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

解释

  1. 客户端:使用 request 发送包含图片的数据流。
  2. 服务器端:使用 formidable 解析接收到的数据,并将文件保存到指定路径。

确保 Content-Type 被设置为 multipart/form-data,这样才能让 formidable 正确解析请求体中的文件数据。

回到顶部