Question:
You need to transfer the file itself and not the data about the file
auth.service.ts
I accept an object with data from the registration component register.component.ts
registerUser(user) {
console.log(user);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.domain + 'authentication/register',
JSON.stringify(user), options).map(res => res.json());
}
console.log
displays all the necessary data, including the file itself
{
address: "124124124"
avatar: File {name: "big_5ae4786f899b2c8bf63b3ee481f0daf2503e402b.jpg",
lastModified: 1503854933277, lastModifiedDate: Sun Aug 27 2017 20:28:53
GMT+0300 (RTZ 2 (зима)), webkitRelativePath: "", size: 436719, …}
birthday: {day:"1",month:"January",year:"1967"}
email: "example@gmail.com"
password: "password"
phone: "123123412"
username: "Denis"
}
Sending data …
authentication.js(express.js routing)
We are accepting data …
router.post('/register', upload.any(), (req, res) => {
console.log(req.body);
)};
But now the file is missing in the request body.
{
address: "124124124"
avatar: {}
birthday: {day:"1",month:"January",year:"1967"}
email: "denisod93@gmail.com"
password: "kamekadZ227@"
phone: "123123412"
username: "Denis"
}
What am I doing in the registerUser()
function and what parameters are required for the POST method?
Answer:
Question: Do you want to transfer data about the file or the file itself?
JSON.Stringify
converts everything to a string, including your File.
While console.log
prints a file description "object", then Stringify in most browsers prints either an empty string or a string like [Object {}]
.
If you want to transfer the file, then there are two options:
-
you need to send the file and JSON separately, as two separate parameters, through
let formData: FormData = new FormData(); formData.append('avatar', file, file.name); formData.append('user', user); return this.http.post(this.domain + 'authentication/register', formData, options)....
-
Or drive the file through base64