首页 > 解决方案 > node.js基本文件上传expess-fileupload错误

问题描述

express-fileupload 示例中使用示例

<pre>   
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

// default options
app.use(fileUpload());

app.post('/upload', function(req, res) {
 if (Object.keys(req.files).length == 0) {
 return res.status(400).send('No files were uploaded.');
}

// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file

让 sampleFile = req.files.sampleFile;

// Use the mv() method to place the file somewhere on your server
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
 if (err)
 return res.status(500).send(err);

 res.send('File uploaded!');
 });
 }); <code>

我收到这个错误

nodejs server1.js /var/www/html/express/server1.js:14 让 sampleFile = req.files.sampleFile; ^^^

SyntaxError:在严格模式之外尚不支持块范围的声明(let、const、函数、类)

我敢肯定,事情很简单。即使在此处粘贴代码,'let' 语句也是孤立的。

标签: node.jsexpress

解决方案


在块范围的声明中,let关键字告诉 NodeJS 你声明的变量将只存在于代码的最内层控制块中。这可能是一个函数或函数中的一组花括号,最常见于循环中。早期版本的节点不支持它。查看该nvm工具以了解如何根据需要在不同版本的节点之间切换。通常您会希望使用最新的长期支持版本。

在 上cannot find module,您正在寻找用于npm安装节点模块的工具。它找不到express-fileupload,所以你想从 npm 安装那个文件。您可以使用以下方式安装模块:

npm install express-fileupload

或者用简写npm i express-fileupload

如果您碰巧使用的是非常旧版本的 npm,最好使用

npm i express-fileupload --save

这会将您的项目依赖于express-fileupload包的面存储在一个名为 package.json 的文件中,以便 npm 稍后在依赖管理(例如重新安装包、审计或在部署到其他系统时安装依赖项)时知道这一点。较新版本的 npm 会自动执行此操作。npm i express-fileupload --save-dev如果您只在开发环境中而不是在生产环境中关心这种依赖关系,您会使用。


推荐阅读