I have a reactive form in Angular 8. On form submission, I need to post the values along with the uploaded file to an API. But I am not quite sure of how to post the file along with values.
<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
<div>
<label for="desc">Description</label>
<input type="text" id="desc" formControlName="desc"/>
</div>
<div>
<label for="summary">Summary</label>
<textarea id="summary" formControlName="summary"></textarea>
</div>
<div formGroupName="contact">
<div>
<label for="name">Name</label>
<input type="text" id="name" required formControlName="name"/>
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" formControlName="email"/>
</div>
</div>
<div>
<label for="file">Upload File</label>
<input type="file" id="file" formControlName="file">
</div>
<button type="submit">Submit</button>
</form>
In component
constructor(public httpService: HttpRequestService) { }
onSubmit() {
this.httpService.postData(this.detailsForm.value).then(
(result) => {
this.jsonResponse = result;
},
(err) => {
this.errorResponse = 'Sorry, there was an error processing your request!';
}
)
}
In service
postData(detailsData) {
const headers = new HttpHeaders(
{ 'Content-Type': 'multipart/form-data' }
);
return new Promise((resolve, reject) =>{
this.http.post('http://localhost:3000/postData', detailsData, { headers: headers })
.subscribe(res => resolve(res), err => reject(err))
});
}
In backend, just for testing purpose
const express = require("express");
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
// Configuring body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(3000, () => {
console.log("Server running on port 3000");
});
app.post("/postData", (req,res) => {
console.log(req.body);
});
All the values are logged, but for file I am only getting the path value. How do I get the contents of file(I need to upload and send Excel File).