我正在创建一个从 node.js 中的多个客户端接收文件的应用程序。为此,我使用 express multer 节点模块。
在以下代码中,我处理文件上传:
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename){
return filename;
},
onFileUploadStart: function(file){
console.log("file size: " + file.size);
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file){
console.log(file.fieldname + ' uploaded to ' + file.path);
done = true;
},
onFileUploadData: function(file, data){
//console.log("data being received " + data);
}
}));
但是当我进入里面时onFileUploadStart
是file.size
0。
multer 文件对象是具有以下属性的 JSON 对象,因此我知道 size 属性存在。
fieldname - Field name specified in the form
originalname - Name of the file on the user's computer
name - Renamed file name
encoding - Encoding type of the file
mimetype - Mime type of the file
path - Location of the uploaded file
extension - Extension of the file
size - Size of the file in bytes
truncated - If the file was truncated due to size limitation
buffer - Raw data (is null unless the inMemory option is true)
为什么大小返回为 0?
编辑: 虽然文件大小返回 0 文件的其他属性,如 file.originalname 正在工作并返回正确的名称。
EDIT2: 当我在 onFileUploadStart 函数中打印文件时,我得到以下属性和相关值:
{
filename: 'userFile',
originalname: 'name.png',
name: 'name.png',
encoding: '7bit',
mimetype: 'image/png',
path: 'uploads\\name.png',
extension: 'png',
size: 0,
truncated: null,
buffer: null
}
为什么 multer 节点模块可以正确发送除文件大小之外的所有内容?
编辑3:
request.body 打印以下内容:
{ submit: 'upload file' }
这很奇怪。我在以下代码中打印请求正文:
app.post('/upload/', function(request, response){
console.log(request.body);
if (done == true){
response.end('file uploaded');
}
});
index.html 文件,客户端可以在其中上传文件:
<html>
<head>
</head>
<body>
<form id= "upload" enctype= "multipart/form-data" action="/upload/" method="post">
<input type="file" name="userFile" />
<input type="submit" name="submit" value="upload file" />
</form>
</body>
</html>