Reputation: 383
My ionic app is sometimes used in browser and I need to upload some images.
I have implemented a code to select my file, then I have a formData
type where I put my image in.
I am trying to upload my file to the server using a post request but I am not sur how to do it.
When I receive my file in my php code, I INSERT it inside my db, I got a blob file in my db but I think it's not the image, it's way to small...
html file :
<input
style="display: none"
type="file" (change)="onFileChanged($event)"
#fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="onUpload()">Upload!</button>
ts file :
onFileChanged(event) {
this.selectedFile = <File>event.target.files[0];
console.log(this.selectedFile);
}
onUpload() {
// upload code goes here
// this.http is the injected HttpClient
let uploadData = new FormData();
uploadData.append('file', this.selectedFile, this.selectedFile.name);
console.log(this.selectedFile);
this.http.post(this.server + 'saveExo.php', this.selectedFile)
.subscribe(resData => {
console.log(resData);
});
}
php file :
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Content-Type: application/json; charset=UTF-8');
include "db.php";
$postjson = json_decode(file_get_contents('php://input'), true);
$today = date('Y-m-d');
if ( isset( $_POST) ) {
$result = json_encode(array('receive' => 'ok'));
$query = mysqli_query($mysqli, "INSERT INTO EXO SET
image = '$_POST'");
echo $result;
} else {
$result = json_encode(array('receive' => 'nothing'));
echo $result;
}
?>
Here is what I get inside my db :
Thank you for your help, I think it's the wrong way to save my image in my db...
Upvotes: 1
Views: 300
Reputation: 7406
my solution is to convert your image to base64 in client-side using: base64 then store it on the server. to view it again, send the base64 to the client and convert again using base64 plugin.
Upvotes: 1