I want to implement a file upload feature in my angular2 project. I want to restrict user to upload only files of certain type: .pdf, .doc and .docx.
The following is my code for fileChange:
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
console.log('file',file);
var formData = new FormData();
formData.append('file', file, file.name);
var options = { content: formData };
console.log('options',options);
var jsonBody = {};
jsonBody['submoduleid'] = '3789e76489fc4e118f8dffad107fbbbd';
jsonBody['file'] = options;
console.log('jsonbody',jsonBody);
this.Module7Service.uploadFile(jsonBody)
.subscribe(
data => {
console.log(data.Response)
if (data.message == "module7 finish") {
console.log('after success',jsonBody)
alert('done file uploaded successfully');
}
else{
alert('not uploaded');
}
});
}
}
The following is my code for uploadFile:
//service code
uploadFile(file){
const body = file;
const headers = new Headers({
'Authorization': window.localStorage.getItem('token'),
'content_type' : 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
'Accept': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'Source': 'WEB'
});
return this.http.post(this.apiUrl + 'module7/', { body: body }, { headers: headers })
.map(
res => {
return res.json();
},
error => alert("आपली विनंती आत्ता पूर्ण करू शकत नाही, कृपया पुन्हा प्रयत्न करा."));
}
And this is the input HTML tag:
<input type="file" (change)="fileChange($event)"
placeholder="Upload file" accept=".pdf,.doc,.docx">
I have added all required key, formdata etc. but when I upload a file I'm getting some error:
XMLHttpRequest cannot load "apiurl". Request header field Access-Control-Allow-Methods is not allowed by Access-Control-Allow-Headers in preflight response.
Here is an image of the error in the browser console.
What could be de source of this problem?