我正在创建一个表格,允许用户上传他们的文件。我在前端使用Angular,在后端使用Node.js / MySQL。但是,我得到一个错误。当我尝试将文件从Angular发送到Node.js时,不会收到该文件。我在堆栈溢出的某个地方读到,有人可以在http标头中发送文件。有人可以告诉我我在做什么错吗?这是我的代码:
xxxx.component.html(角度)
<div class="input-group">
<div class="input-group-prepend">
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" [(ngModel)] = "fU" name =
"FileUpload" id="inputGroupFile01"
aria-describedby="inputGroupFileAddon01" required>
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
xxxx.component.ts(角度)
private onCreatePosts(form: NgForm)
{
this.http.post('http://localhost:3000/post', form.value)
.subscribe(responseData => {
console.log(responseData);
}
,error => {
this.connectionToServerFailed = true;
});
}
Node.js
router.post("/post", (req, res) =>{
var fileupload = req.body.FileUpload;
console.log(fileupload);
console.log(fileupload.name);
})
这是我尝试上传文件时得到的输出:
C:\ fakepath \ testfile.docx
未定义
我尝试了不同的方法,但仍然无法继续进行。谁能告诉我为什么我得到这个不确定的错误和fakepath错误。
编辑:当我尝试访问文件时,它仅打印路径而不是文件。角度Http请求仅发送文件的路径,而不发送文件本身。编辑:再次编辑此问题,以便有人可以提供帮助。编辑:我曾尝试使用许多不同的东西,但没有任何东西对我有用。node.js仅获取文件的路径,而不获取文件本身。
开箱即用的文件不会成为请求的一部分;它们必须临时存储在Node.js的磁盘或内存中。尝试使用类似multer的方法:https ://medium.com/javascript-in-plain-english/uploading-files-using-multer-on-server-in-nodejs-and-expressjs-5f4e621ccc67
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句