Dan*_*iel 22 javascript node.js express multer
我正在使用multer上传我的图像和文档,但这次我想限制上传,如果图像的大小> 2mb.如何找到文档文件的大小?到目前为止,我尝试如下,但没有工作.
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, common.upload.student);
},
filename: function (req, file, callback) {
console.log(file.size+'!!!!!!!!!!!!!!')======>'Undefined'
var ext = '';
var name = '';
if (file.originalname) {
var p = file.originalname.lastIndexOf('.');
ext = file.originalname.substring(p + 1);
var firstName = file.originalname.substring(0, p + 1);
name = Date.now() + '_' + firstName;
name += ext;
}
var filename = file.originalname;
uploadImage.push({ 'name': name });
callback(null, name);
}
});
Run Code Online (Sandbox Code Playgroud)
谁能帮帮我吗?
小智 43
var fs = require("fs"); //Load the filesystem module
var stats = fs.statSync("myfile.txt")
var fileSizeInBytes = stats["size"]
//Convert the file size to megabytes (optional)
var fileSizeInMegabytes = fileSizeInBytes / 1000000.0
Run Code Online (Sandbox Code Playgroud)
要么:
function getFilesizeInBytes(filename) {
var stats = fs.statSync(filename)
var fileSizeInBytes = stats["size"]
return fileSizeInBytes
}
Run Code Online (Sandbox Code Playgroud)
If you use ES6 and deconstructing, finding the size of a file in bytes only takes 2 lines (one if the fs module is already declared!):
const fs = require('fs');
const {size} = fs.statSync('path/to/file');
Run Code Online (Sandbox Code Playgroud)
Note that this will fail if the size variable was already declared. This can be avoided by renaming the variable while deconstructing using a colon:
const fs = require('fs');
const {size: file1Size} = fs.statSync('path/to/file1');
const {size: file2Size} = fs.statSync('path/to/file2');
Run Code Online (Sandbox Code Playgroud)
小智 6
另外,你可以使用 NPM filesize 包:https : //www.npmjs.com/package/filesize
这个包使事情变得更加可配置。
var fs = require("fs"); //Load the filesystem module
var filesize = require("filesize");
var stats = fs.statSync("myfile.txt")
var fileSizeInMb = filesize(stats.size, {round: 0});
Run Code Online (Sandbox Code Playgroud)
更多示例:https :
//www.npmjs.com/package/filesize#examples
归档时间: |
|
查看次数: |
25881 次 |
最近记录: |