I am trying to upload a file to the server so what I did was I converted my data json into formData, appended file to it and then sent to a request. The Request Payload that I see in the requesPayload is not JSON but is something else.
Here attached is the request payload screenshot :
Here is the component function code :
doSubmit(data){
const fd = new FormData();
fd.append('name','Tirthraj');
fd.append('file',this.myFile);
for (var key in data) {
if (data.hasOwnProperty(key)) {
fd.append(key,data[key])
console.log(key + " -> " + data[key]);
}
}
this.myService.doUploadDataWithFile(fd).then();
}
Here is the service function :
doUploadDataWithFile(data): Promise<any> {
let headers = new Headers();
// headers.append('Content-Type', 'multipart/form-data');
headers.append('Content-Type', 'undefined');
let options = new RequestOptions({ headers: headers });
console.log("ADDElearning DATA", data);
return this.http.post("SERVER_API", data, options).toPromise();
}
Here is the request payload :
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="name"
Tirthraj
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="file"; filename="524347_335264113233857_1091003137_n.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="module_title"
312
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="module_synopsis"
123
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="estimated_time"
321
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="module_type"
scorm12
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="article_title"
123312
------WebKitFormBoundary5Ga9J56YQxt16Ey4
Content-Disposition: form-data; name="article_description"
321
------WebKitFormBoundary5Ga9J56YQxt16Ey4--
I want it to be like JSON Object and not what it is right now. Could anybody help?
As you have mentioned you want to send file along with form data the thing which you have done is absolutely right. only thing is missing is correct way to access that file in php. as you are sending form-data. it means you are sending whole form with name of that input field.
so you can access it like
echo $_POST['module_title'];
var_dump($_FILES['file']);
var_dump($_FILES['file1'])
$filename = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'],'uploads/'.$filename);