How to move ionic video capture to file_put_contents() in php - php

we created an ionic app which captures video but we are facing challenges saving this video to a directory in on the server. I have searched online for this but couldn't find a tutorial about it.
On the code below, the video name was saved in the videos folder instead of the actual video
//Upload video php part
$postjson = json_decode(file_get_contents('php://input'), true);
if(!empty($postjson['video'])){
$video = $postjson['video'];
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now -> format('YmdHisu');
$upload_folder = "videos";
$path ="$upload_folder/$id.mp4";
$actualpath = "http://url/incident/api/$path";
file_put_contents($path,$video);
}
On the ionic part, I have this:
captureVideo() {
let options: CaptureVideoOptions = {
limit: 1,
duration: 120
}
this.mediaCapture.captureVideo(options).then((res: MediaFile[]) => {
let capturedFile = res[0];
let fileName = capturedFile.name;
let dir = capturedFile['localURL'].split('/');
dir.pop();
let fromDirectory = dir.join('/');
var toDirectory = this.file.dataDirectory;
this.ivideo = fileName;
this.viddir = dir;
console.log("video captured "+this.ivideo);
this.file.copyFile(fromDirectory , fileName , toDirectory , fileName).then((res) => {
this.storeMediaFiles([{name: fileName, size: capturedFile.size}]);
},err => {
console.log('err: ', err);
});
},
(err: CaptureError) => console.error(err));
}
Sending to the server using post method in code summary:
var headers = new Headers();
headers.append('Content-Type', 'application/json' );
//headers.append('Access-Control-Allow-Methods', 'POST' );
headers.append('Content-Type', 'multipart/form-data');
let options = new RequestOptions({ headers: headers });
let data = {
aksi : 'insert_incident',
title: this.title.value,
descr: this.descr.value,
images : this.cameraData,
video: this.ivideo,
};
this.http.post(this.global.serverAddress+"api/getCategories.php", data, options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
if(res=="Done"){
let alert = this.alertCtrl.create({
title:"Done",
subTitle: "Sent",
buttons: ['OK']
});
alert.present();
}else
{
let alert = this.alertCtrl.create({
title:"ERROR",
subTitle:(res),
buttons: ['OK']
});
alert.present();
}
}

Related

How to upload files from react native app to PHP server?

I developed a PHP project, now I am working on connecting it to react native app. However, I tried many codes to upload image to the server nothing works.
Here is my code example,
const uploadImage = async () => {
// Check if any file is selected or not
if (singleFile != null) {
// If file selected then create FormData
const fileToUpload = singleFile;
const data = new FormData();
data.append('file_attachment', fileToUpload);
// Please change file upload URL
fetch(
'http://192.168.8.105/insaf/mobileConnection/upload.php',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
).then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson[0].Message == "Success") {
navigation.replace('ReqPriceList');
} else {
//setErrortext(responseJson.msg);
console.log('Please check');
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
} else {
// If no file selected the show alert
alert('Please Select File first');
}
};
And for the PHP server side (upload.php), here is the code
if(!empty($_FILES['file_attachment']['name']))
{
$target_dir = "../assets/files/request/";
if (!file_exists($target_dir))
{
mkdir($target_dir, 0777);
}
$target_file =
$target_dir . basename($_FILES["file_attachment"]["name"]);
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo json_encode(
array(
"status" => 0,
"data" => array()
,"msg" => "Sorry, file already exists."
)
);
die();
}
// Check file size
if ($_FILES["file_attachment"]["size"] > 50000000) {
echo json_encode(
array(
"status" => 0,
"data" => array(),
"msg" => "Sorry, your file is too large."
)
);
die();
}
if (
move_uploaded_file(
$_FILES["file_attachment"]["tmp_name"], $target_file
)
) {
echo json_encode(
array(
"status" => 1,
"data" => array(),
"msg" => "The file " .
basename( $_FILES["file_attachment"]["name"]) .
" has been uploaded."));
} else {
echo json_encode(
array(
"status" => 0,
"data" => array(),
"msg" => "Sorry, there was an error uploading your file."
)
);
}
}
I got this code from here https://aboutreact.com/file-uploading-in-react-native/
And I am getting
this error
Can anyone help me?
Any alternative solution will be fine.
Edit:
based on #Sadia Chaudhary code this function works
let uploadImage = async () => {
//Check if any file is selected or not
if (singleFile != null) {
//If file selected then create FormData
const fileToUpload = singleFile;
console.log("fileToUpload is " + fileToUpload);
const uriPart = fileToUpload[0].uri;
const fileExtension = fileToUpload[0].name.split('.')[1];
console.log("fileExtension is " + fileExtension);
const data = new FormData();
//const uriPart = fileToUpload.split('.');
//const fileExtension = uriPart[uriPart.length - 1];
data.append('file_attachment', {
uri: uriPart,
name: `photo.${fileExtension}`,
type: `image/${fileExtension}`
});
let res = await fetch(
'http://myIp/insaf/mobileConnection/uploads.php',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
);
let responseJson = await res.json();
if (responseJson.status == 1) {
alert('Upload Successful');
}
} else {
//if no file selected the show alert
alert('Please Select File first');
}
};
The error has nothing to do with the image upload. You are facing this error because of response.json(). Also, try to convert image like this.
//retrive the file extension of your photo uri
const uriPart = imageSource.split('.');
const fileExtension = uriPart[uriPart.length - 1];
formData.append('photo', {
uri: imageSource,
name: `photo.${fileExtension}`,
type: `image/${fileExtension}`
});

how to submit input data along with ng2 file upload angular ionic

Please I want to send some text data with file upload(ng2 file upload) in angular ionic. I am new to angular and ionic as well. I have tried so many options but I don't seem to get a way out. I am using Php as a backend.I am able to send the file only but not the input data like username. Meanwhile I am able to log the input data that's username on the console but the server response is null. And it never inserts in my database. This is my code.
public fileUploader: FileUploader = new FileUploader({});
ngOnInit() {
this.fileUploader = new FileUploader({ url: "http://localhost/paat/server/post.php"});
this.fileUploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
form.append('body', this.body);
form.append('username', this.username);
// Add file to upload
form.append('file', fileItem);
fileItem.withCredentials = false;
return { fileItem, form };
};
}
fileOverBase(event): void {
this.hasBaseDropZoneOver = event;
}
//return files from ng2 upload
getFiles(): FileLikeObject[] {
return this.fileUploader.queue.map((fileItem) => {
return fileItem.file;
});
}
// the upload method where the post to server is made
uploadFiles() {
let bodys = {
body:this.body,
username:this.username,
};
let files = this.getFiles();
let requests = [];
files.forEach((file) => {
let formData = new FormData();
formData.append('file' , file.rawFile, file.name);
formData.append('body' , this.body);
formData.append('username' , this.username);
requests.push(this.uploadingService.uploadFormData(formData));
});
concat(...requests).subscribe(
(res) => {
console.log(res);
console.log(this.body);
console.log(this.username);
console.log(this.file.name);
},
(err) => {
console.log(err);
}
);
}
this is my uploadservice.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class UploadingService {
API_SERVER: string = "http://localhost/paat/server/post.php";
constructor(private http: HttpClient) { }
public uploadFormData(formData) {
return this.http.post<any>(`${this.API_SERVER}`, formData);
}
}
This is my backend code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods:POST,GET,PUT,DELETE");
header("Access-Control-Max-Age:86400");
header("Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With");
$con = mysqli_connect("localhost", "root", "", "social");
$postjson = json_decode(file_get_contents('php://input'), true);
$filename = $_FILES['file']['name'];
$meta = $_POST;
$targetDir = "assets/images/posts/";
$destination = $targetDir . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
$body = $postjson['body'];
$date_added = date("Y-m-d H:i:s");
//get username
$added_by = $postjson['username'];
//if user is on own profile, user_to is 'none'
$targetfile = $destination;
$user_to ="none";
$query = mysqli_query($con,"INSERT INTO posts VALUES(NULL, '$body', '$added_by', '$user_to', '$date_added', 'no', 'no', '0', '$targetfile')");
What am I doing wrong? Please help.
I have found out what I was doing wrong. The problem was with my backend code. It was the way I was retrieving the formdata values from the request. So I changed
$body = $postjson['body'];
$added_by = $postjson['username'];
to
$body = $_POST['body'];
$added_by = $_POST['username'];
Also I modified my ngOnInit() method and the instance of fileuploader method to
public fileUploader: FileUploader = new FileUploader({ url: "http://localhost/paat/server/post.php"});
ngOnInit() {
this.fileUploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
form.append('body', this.body);
// Add file to upload
form.append('file', fileItem);
form.append('username', this.username);
fileItem.withCredentials = false;
return { fileItem, form };
};
}
and it now works.

Failed upload image to server with base64Encode

I use image picker to get photo from camera then upload it to the server with base64Encode, like this
http.post( api('file/update_pic_item/2'), body: data, headers: {HttpHeaders.authorizationHeader: prefs.getString('token'), "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"}).then((response) async {
toast('Success');
Map res = json.decode(response.body); print(res);
});
By server I got this message
The pic1 must be an image., The pic1 must be a file of type: jpeg, jpg, bmp, png
I use lumen for my backend,
$this->validate($request, [
'pic1' => 'nullable|image|mimes:jpeg,jpg,bmp,png|max:10240', ]);
$upload_path = 'images/items';
if ($request->hasFile('pic1')) {
$pic1 = $request->file('pic1');
$ext1 = $pic1->getClientOriginalExtension();
if ($pic1->isValid()) {
$pic_name = Carbon::now()->format('YmdHs') . "a." . $ext1;
$pic1->move($upload_path, $pic_name);
$item->update(['pic1' => $pic_name]);
}
}
How to solve this problem? thank you so much for your help
Use this code to upload image on server
Future upload(File imageFile)async{
var stream= new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length= await imageFile.length();
var uri = Uri.parse('imageUrl');
var request = new http.MultipartRequest("POST", uri);
var imageUri = 'salati_${widget.user.user_id}_${DateTime.now().millisecondsSinceEpoch}'+imageFile.path.substring(imageFile.path.lastIndexOf("."));
var multipartFile = new http.MultipartFile("image", stream, length, filename: basename(imageUri));
request.files.add(multipartFile);
var response = await request.send();
if(response.statusCode==200){
print("Image Uploaded");
}else{
print("Upload Failed");
}
}

Upload file to server ionic and php

I have code that sends an image to my server and everything works fine. However i am now truing to send a file to my server using an input tag in ionic However i cant seem to get it working.
I get an error from the php file saying undefined index 'file'
HTML
<ion-col>
<ion-label>Add a File</ion-label>
<ion-input type='file' [(ngModel)]="fileName"></ion-input>
</ion-col>
TS file
addFile() {
this.addService.addFile(this.fileName).subscribe(res => {
console.log(res);
});
}
service
addFile(file) {
let headers = new HttpHeaders();
// headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Authorization', '' + this.token);
const formData = new FormData();
formData.append('file', file);
return this.http.post<any>('http://domain.fileUpload.php', formData, {headers});
}
PHP API
$target_path = "files/";
$target_path = $target_path . basename( $_FILES['file']['name']);
$findDate = date("Y-m-d");
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
header('Content-type: application/json');
$data = ['success' => true, 'message' => 'Upload and move success'];
echo json_encode( $data );
} else {
header('Content-type: application/json');
$data = ['success' => false, 'message' => 'There was an error uploading the file (folder), please try again!'];
echo json_encode( $data );
}
uploadMethod
uploadFile: ''; // from ngModel
fileUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'file',
fileName: '.png',
chunkedMode: false,
};
console.log(this.uploadFile);
fileTransfer
.upload(this.uploadFile, 'http://domain/fileUpload.php',
options
)
.then(
data => {
console.log(data + 'Uploaded Successfully');
// console.log(JSON.parse(data.));
// let res = JSON.parse(data);
let res = data;
if (res['success']) {
console.log('True');
}
},
err => {
console.log(err);
}
);
}
Blow is the Example Code:
import { Platform } from 'ionic-angular';
checkPlatform: boolean = fasle;
constructor(public plt: Platform) {
if (this.plt.is('ios')) {
this.checkPlatform == true; // if platform ios this will be true
}
if (this.plt.is('android')) {
this.checkPlatform == true; // if platform androidthis will be true
}
}
imageUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'image',
fileName: '.png',
chunkedMode: false,
//mimeType: "image/jpeg",
}
fileTransfer.upload(path, 'https://yourDomain.com/api/imageUpload', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
console.log(JSON.parse(data.response));
let res = JSON.parse(data.response);
if (res.success == true) {
// do whats ever you want to do
}
}, (err) => {
console.log(err);
});
}
Pass the cordova file path as parameter in this function.
inside you HTML template show buttons or input type like this:
<input type="file" *ngIf="checkPlatform == true">
if you see this you can notice allowed types are :
export type TextFieldTypes = 'date' | 'email' | 'number' | 'password' | 'search' | 'tel' | 'text' | 'url' | 'time';
if you want to upload files follow this link i think you will find the answer
I check your code and as i see file added to FormData is filename with string Type, not File or Blob Data Type. So in this case it will not send file into $_FILES, it actually send its value to $_POST in your PHP Server. In summary, File and Blob Type will be sent to $_FILES, other data types will be sent to the appropriate global variables.
There is also a good example on how to validate your file in PHP Server: https://www.php.net/manual/en/features.file-upload.php

How to upload photo into Server using Mosync

I have a problem in uploading photo into server which is taken by camera.
I have tried to used the code in Mosync site but it doesn't work.
In the sample code below,
my app always return "Could not upload photo - error: 3"
app.uploadPhoto = function(fileURL)
{
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = app.getMimeType(options.fileName);
options.params = null;
var transfer = new FileTransfer();
transfer.upload(
fileURL,
"http://dev.mosync.com/mobilelua/PhotoGallery/upload.php",
function(result)
{
alert("Photo uploaded");
},
function(error)
{
alert("Could not upload photo - error: " + error.code);
},
options);
};

Categories