Node.js 从ExpressJS请求文件获取二进制数据

Node.js 从ExpressJS请求文件获取二进制数据,node.js,Node.js,我在客户端有一个表单,是上传一个文件 <form method="post" action="/"> <input type="file"/> </form> 使用ExpressJS中间件,如 注意:以下示例不适用于生产环境。HTML代码和express js后端都没有采用任何类型的安全性。在生产环境中使用此示例会使您的系统和网络受到攻击。 另请注意:我假设您对express js有一些非常基本的了解,包括如何制作简单的GET和POST路线。 假设我

我在客户端有一个表单,是上传一个文件

<form method="post" action="/">
    <input type="file"/>
</form>

使用ExpressJS中间件,如

注意:以下示例不适用于生产环境。HTML代码和express js后端都没有采用任何类型的安全性。在生产环境中使用此示例会使您的系统和网络受到攻击。

另请注意:我假设您对express js有一些非常基本的了解,包括如何制作简单的GET和POST路线。

假设我有一个包含以下简单HTML的页面,允许用户将任何类型和大小的文件上载到我的网站:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Upload file to ExpressJS backend</title>
</head>
<body>
<form enctype="multipart/form-data" action="/do-upload" method="post">
  <input type="file" name="file_from_user"/>
  <input type="submit" value="Submit"/>
</form>
</body>
</html>
让express js轻松地接受单个文件上传,然后将sad上传隐藏在目录中的某个位置就是这么简单。不过,正如我所说,这还没有准备好生产。它需要安全性,我把它作为一个挑战留给你去解决

资料来源和进一步阅读:


你能更清楚地解释一下吗:我是个新手。太多了@泰先生,我正在做一个例子。当我完成后,我会在这里发布另一条评论,并更新我的答案。太多了!但是我怎样才能得到这个文件的数据内容??它可以是req.file.data或req.file.content吗?Tks@M.Tae
req.file.buffer
是包含文件内容的缓冲区对象。您可以读取节点6中的缓冲区。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Upload file to ExpressJS backend</title>
</head>
<body>
<form enctype="multipart/form-data" action="/do-upload" method="post">
  <input type="file" name="file_from_user"/>
  <input type="submit" value="Submit"/>
</form>
</body>
</html>
var express = require('express'),
  multer = require('multer'),

  // Set up the middleware, which automatically handles files uploaded to it.
  // The "dest" property specifies the location to save uploaded files.
  // You will need to make sure this directory exists.
  upload_middleware = multer({dest: 'tmp/uploads/'}),

  app = express(),

  // This is the name of the <input> element from the HTML that will
  // send the file to the server.
  form_element_name = 'file_from_user';

// The second parameter is how one injects middleware into a route in express js.
app.post('/do-upload', upload_middleware.single(form_element_name), function (request, response) {
  console.log('Got a file!');

  // The multer middleware adds the "file" property 
  // to the request object. The file property contains useful
  // information about the file that was uploaded.

  console.log('The original filename was: "%s".', request.file.originalname);
  console.log('I saved the file to: %s.', request.file.path);
  console.log('The file is %s bytes in size.', request.file.size);

  // Finish the request with an HTTP 200 code and an informative message, so we don't leave user
  // hanging in his or her browser.
  response
    .status(200)
    .send('File uploaded successfully!');
});

// ... other routes
// ... app.listen call that starts your server