I am trying to upload the file by web browser but i can't do that. When i save this api by postman then uploaded the file but i can't upload the file by trying web browser. When i try to upload the file by web browser then I got an error like "SyntaxError: Unexpected token - in JSON at position 0" in my server side.
I am using NodeJS, ExpressJs as a back-end and Angular 6 as a front-end.
Angular
html
<div>
<div>
<input type="file" (change)="createFormData($event)">
</div>
<button (click)="upload()">Upload</button>
</div>
ts
export class PhotographComponent implements OnInit {
selectedFile: File = null;
fd = new FormData();
constructor(private formBuilder: FormBuilder, private httpClient:
HttpClient) {}
ngOnInit() {}
createFormData(event) {
this.selectedFile = <File>event.target.files[0];
this.fd.append('photo', this.selectedFile, this.selectedFile.name);
}
upload() {
this.httpClient.post(environment.apiUrl + 'photographs', this.fd)
.subscribe( result => {
console.log(result);
});
}
}
NodeJs
const { Photograph, validate } = require('../models/photograph');
const multer = require('multer');
const express = require('express');
const router = express.Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({
storage: storage
})
// save photograph
router.post('/', upload.single('photo'), (req, res) => {
console.log(req.file);
const filename = req.file.filename;
const path = req.file.path;
res.json({message: 'File uploaded'});
})
module.exports = router;
Please help me to find a solution to upload a file. Thanks.