[英]How to encoded files in base64 in nodejs after getting details from client-side using multer
I am sendind file-details from angular to my app.js as我将文件详细信息从 angular 发送到我的 app.js 作为
onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
const formData = new FormData();
formData.append('file', file);
const r = new XMLHttpRequest();
r.open('POST', '/user/upload');
r.send(formData);
}
then in app.js然后在 app.js
const multer = require('multer');
const upload = multer({dest:'./pics/'});
router.post('/upload', upload.single('image'), (req,res) => {
const body = req.file;
console.log(body);
const base64Data = new Buffer(JSON.stringify(body)).toString("base64");
console.log(base64Data);
}
and my console.log(body)
gives我的
console.log(body)
给出
{ fieldname: 'image',
originalname: '21329726_1866651723650020_188839340_o.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './pics/',
filename: '5146c9818ff517c426e34ad84ff3513f',
path: 'pics/5146c9818ff517c426e34ad84ff3513f',
size: 94093
}
Now the problem is here -现在问题来了——
1 - I don't want to upload my image/pdf
file in any folder, But it is uploading in './pics/'
. 1 - 我不想在任何文件夹中上传我的
image/pdf
文件,但它正在上传'./pics/'
。
2- I want to upload that file in cloudinary
thats why I want to generate base64
of that file but when I am generating base64
and and uploading that in cloud, it gives an error. 2- 我想在
cloudinary
上传该文件,这就是为什么我想生成该文件的base64
,但是当我生成base64
并将其上传到云中时,它会出错。
I think that it is not the correct method for encoding in base64
OR I am encoding wrong data format.我认为这不是在
base64
编码的正确方法,或者我正在编码错误的数据格式。
Please help me.请帮我。
I would suggest you to use multiparty .我建议你使用multiparty 。 A simple and easy solution handle form-data.
一个简单易用的解决方案处理表单数据。 Here you can upload files without saving it.
在这里您可以上传文件而不保存它。 I'm using this for save files in
AWS S3
我正在使用它在
AWS S3
保存文件
router.post('/upload',(req,res)=>{
let form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
//here files is array
const base64Data = new Buffer(JSON.stringify(body)).toString("base64");
console.log(base64Data);
});
});
Or else you simply omit the dest
object.否则,您只需省略
dest
对象。 The file will be stored in memory instead of a physical location:该文件将存储在内存中而不是物理位置:
By providing the options object (in this case {dest:'./pics/'}
), you're telling multer
that you want to store the files in that directory.通过提供选项对象(在本例中为
{dest:'./pics/'}
),您告诉multer
您要将文件存储在该目录中。 Instead, configure it to hold the files in memory:相反,将其配置为将文件保存在内存中:
var storage = multer.memoryStorage()
var upload = multer({ storage: storage })
According to the docs, the file
object should also include a buffer
property, which contains the file data.根据文档,
file
对象还应包含一个buffer
属性,其中包含文件数据。 You should be able to do:你应该能够做到:
console.log(body.buffer.toString("base64"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.