Javascript 从角度侧发送文件后,对Node.js侧的大文件进行编码时出错
我在服务器端以Javascript 从角度侧发送文件后,对Node.js侧的大文件进行编码时出错,javascript,node.js,angular,typescript,Javascript,Node.js,Angular,Typescript,我在服务器端以console.log(body)的形式获取文件 然后通过const base64Data=body.buffer.toString(“base64”)进行编码 但是对于小文件,它工作得很好,但是对于大文件,它会产生问题。它没有正确编码 我认为问题在于,它在收到完整文件之前就开始编码 请给我一些适当的方法来做这件事 这是我的GitHub链接。我认为最好不要在前端将pdf文件转换为base64,因为它会增加请求开销,因为base64的大小更大。最好使用html5 FormData上传
console.log(body)
的形式获取文件
然后通过const base64Data=body.buffer.toString(“base64”)
进行编码
但是对于小文件,它工作得很好,但是对于大文件,它会产生问题。它没有正确编码
我认为问题在于,它在收到完整文件之前就开始编码
请给我一些适当的方法来做这件事
这是我的GitHub链接。我认为最好不要在前端将pdf文件转换为base64,因为它会增加请求开销,因为base64的大小更大。最好使用html5 FormData上传文件和其他请求负载。 尝试这些更改 直接将文件值指定给文档属性
this.uploadForm.patchValue({
document: event.target.files[0]
});
//inside your service enrich your data with FormData ,set content-type to undefined and send it
uploadData (uploadForm) {
//enrich your data is FormData
let fd= new FormData();
// try looping through `this.form.controls` or uploadForm, to assign it property key and value dynamically
fd.append('branch', branch_value);
fd.append('semester', semester_value);
fd.document('document',document_value)
return this.http.post<RegisterResponse>('/user/upload', fd,set_header_config);
}
this.uploadForm.patchValue({
文档:event.target.files[0]
});
//在您的服务中,使用FormData丰富您的数据,将content type设置为undefined并发送它
上传数据(上传表单){
//丰富您的数据是FormData
设fd=newformdata();
//尝试通过“this.form.controls”或uploadForm循环,动态地为其分配属性键和值
fd.追加('branch',branch_值);
fd.追加(‘学期’、学期价值);
fd.文件(“文件”,文件值)
返回此.http.post('/user/upload',fd,set\u header\u config);
}
确保将内容类型正确设置为“未定义”。我已经测试过用angularjs上传文件,但不太熟悉最新的角度变化
您可以查看以下博客:
在/server/routes/user.js中更新此代码
const express = require('express');
const router = express.Router();
// const mongoose = require('mongoose');
const path = require('path');
const multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __basedir + '/upload');
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({
storage: storage,
limits: {
maxFileSize: 1024 * 1024 * 5
}
}).single('filename');
router.post('/upload', upload, (req, res) => {
res.send('uploaded');
});
router.post('/submit', (req, res) => {
console.log(req.body);
});
module.exports = router;
在app.js中添加以下行
global.__basedir=__dirname;
你为什么不直接上传文件,而不是将其转换为base64?你在控制台中得到了完整的响应吗?@Infective我想在
cloudinary
中上传该文件,然后在我的数据库中上传文件的url。@Chellappan是的,如果最后检查的话。最后半部分检查nodeJs直到更好地将文件上传为blob、file或追加到FormData中,您可以在后端将其转换为base64…它成功地发送了文件详细信息,但当我在nodeJs端对其进行编码时,它会以较小的大小对文件进行编码,但是对于大文件,它没有正确编码。我认为对于大文件,在获得全部细节之前,它会开始编码。我使用的是const base64Data=body.buffer.toString(“base64”)编码>用于编码。在哪一端?angular或node。别忘了从angular post请求中添加“内容类型”:“应用程序/八位字节流”头。然后是如何获取req.file
。内部“结束”功能?它给出了一个错误throw new-TypeError('Path必须是字符串。Received'+inspect(Path))代码>我已经更新了代码。我用的是path包,可以用静态路径的文件进行测试。
global.__basedir=__dirname;