对于我的 Angular + Nodejs 应用程序,我有以下上传图像:
文件.ts
handleFileInput(files: FileList) {
var filename = files.item(0);
this.upload(filename).subscribe();
};
upload(fileToUpload: File){
console.log(fileToUpload); //Here I can see all the image data
let obj = {
imageData: fileToUpload,
imageID: "Sample"
};
return this.http.post<any>(url, obj ,{});
}
Run Code Online (Sandbox Code Playgroud)
然后在nodejs中,uploadController.js
private initAPI(): void {
this.router.route('/file')
.post((req, res) => {
console.log(req); //No "body" data
});
}
Run Code Online (Sandbox Code Playgroud)
当我获取数据时,我可以看到以下内容:
body:
imageData: Object {}
imageID: "Sample"
Run Code Online (Sandbox Code Playgroud)
是imageData空的。关于如何发送图像有什么建议吗?
谢谢。
这可以在角度端使用 formData 并在节点端使用 multer 来上传文件来完成。
角部
组件.html
<div>
<div>
<input type="file" (change)="createFormData($event)">
</div>
<button (click)="upload()">Upload</button>
</div>
Run Code Online (Sandbox Code Playgroud)
组件网.ts
selectedFile: File = null;
fd = new FormData();
constructor(private http: HttpClient) {}
createFormData(event) {
this.selectedFile = <File>event.target.files[0];
this.fd.append('file', this.selectedFile, this.selectedFile.name);
}
upload() {
this.http.post(url, this.fd)
.subscribe( result => {
console.log(result)
});
}
Run Code Online (Sandbox Code Playgroud)
节点部分
const express = require('express');
const router = express.Router();
var multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './upload')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({
storage: storage
})
router.post('url', upload.single('file'), (req, res) => {
// the file is uploaded when this route is called with formdata.
// now you can store the file name in the db if you want for further reference.
const filename = req.file.filename;
const path = req.file. path;
// Call your database method here with filename and path
res.json({'message': 'File uploaded'});
});
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8756 次 |
| 最近记录: |