ionic 2 how to HTTP.post image send the server side in ionic 2 / 3 - ios

I'm building an app with Ionic 2. I need to take a photo from gallery or camera and upload this picture to my server. I have this code that opens the Gallery and takes a picture. without base64Image, how can upload image.
private accessGallery(): void {
let options = {
quality: 75,
// sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
// destinationType: this.camera.DestinationType.DATA_URL,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
// encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.imagePicker.getPictures(options).then((results) => {
this.imageURI = new Array();
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
this.imageURI.push(normalizeURL(results[i]));
}
console.log("Body images Name*******:-=" + this.imageURI);
this.uploadFile();
}, (err) => { });
}
uploadFile() {
let body:any = new FormData();
body = {
images: this.imageURI
}
let headers = new Headers({
'token': this.token,
'sid': this.sid,
'user': this.user,
'to': this.to,
'node': this.node,
'type': 'image'
});
let options = new RequestOptions({ headers: headers });
console.log("header ----" + JSON.stringify(headers));
console.log("images data body----" + JSON.stringify(body));
this.http.post(this.apiURL, body, options)
.map(res => res.json())
.subscribe(
data => {
console.log(data);
},
err => {
console.log("ERROR!: ", err);
}
);
}
Error :- ERROR!: Response with status: 0 for URL: null

Related

Camera video not showing on iOS

I'm attempting to access the camera of a current user device and display the camera's video before they can take a picture. It works perfectly on Android and browsers, but not on iPhones for some strange reason. Even when the screen is black, I can still capture a picture. It's just a dark video camera.
Snippet of the code
useEffect(() => {
navigator.mediaDevices
.enumerateDevices()
.then(function (devices) {
devices.forEach(function (device) {
if (device.kind == "videoinput") {
let temp = videoInputs;
temp.push(
device.kind + ": " + device.label + " id = " + device.deviceId
);
setVideoInputs(temp);
}
});
})
.catch(function (err) {
console.log(err.name + ": " + err.message);
});
}, []);
const getVideo = () => {
navigator.mediaDevices
.getUserMedia({
video: {
// width: 1920,
// height: 1080,
facingMode: orientation ? "environment" : "user",
},
})
.then((stream) => {
console.log(stream);
setError("");
setVideoStream(stream);
let video = videoRef.current;
video.srcObject = stream;
video.play();
})
.catch((err) => {
setError(err.toString())
// setError("Permission denied. Turn on your camera to continue");
console.error(err);
});
};
useEffect(() => {
getVideo();
return () => {
stopVideo();
};
}, [orientation]);

Get photo from telegram and post to Strapi via Axios

Hi I'm trying to POST image to Strapi via api/uploads with Axios
With code below I have reponse with code 200, but in Strapi UI get file with no image, but with other parameters.
Something like this
return bot.getFileLink(msg.photo[0].file_id).then((resp) => {
axios.get(resp, { responseType: 'buffer' }) // geting img from telegram link
.then(axres => {
const buffer = Buffer.from(axres.data) // make Buffer obj
const imgdata = new formdata()
imgdata.append('files', buffer, { filename: resp }) // append to FormData object
axios.post(`http://localhost:1337/api/upload`, imgdata, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
})
})
In docs provided example with FormData in body option, but in this case I have error "Bad request 400"
await fetch('/api/upload', {
method: 'post',
body: new FormData(e.target)
});
Solved. With "binary" endocding in Buffer it works perfect.
return bot.getFileLink(msg.photo[0].file_id).then((resp) => {
axios.get(resp, { responseType: 'arraybuffer' })
.then(axres => {
const buffer = Buffer.from(axres.data, 'binary')
const imgdata = new formdata()
imgdata.append('files', buffer, { filename: resp })
console.log(buffer)
axios.post(`http://localhost:1337/api/upload`, imgdata, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then(response => {
console.log('ok');
})
.catch(err => {
console.log(err);
})
})
})

Uploading video to server

I'm using react-native-camera(^0.6.0) in my app, I have to upload the recorded video to server as multipart data. In android they are posting like this,
{
_parts: [
[
'file',
{
name: 'VID_20181130_150959.mp4',
uri: 'file:///storage/emulated/0/DCIM/VID_20181130_150959.mp4',
type: 'video/mp4'
}
]
]
}
but in iOS the file path is returning as assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0&ext=mov but if I post the assets path it's not uploading.
{
_parts: [
[
'file',
{
name: '41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
uri: 'assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
type: 'video/mov'
}
]
]
}
Can anyone help me out with this????
I'm using iPhone 6 for debugging the code,
var url = DomainAPI.lashHostname + '/attachments?token=' + value + '&class=Quick';
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify(formData)
}).then((response) => response.json())
.then((responseData) => {
console.log('responseData------->************$$$$$$$$$$$' + JSON.stringify(responseData));
if (responseData.error.code == 0) {
this.sendFiletoServer(responseData.id, value);
} else {
this.setState({ loading: false });
Actions.pop();
}
}).catch((err) => {
console.log('responseData-------> err ************$$$$$$$$$$$' + JSON.stringify(err));
this.setState({ loading: false });
Actions.pop();
});
See This code worked for me hope it helps
let formData = new FormData();
formData.append("videoFile", {
name: name.mp4,
uri: video.uri,
type: 'video/mp4'
});
formData.append("id", "1234567");
try {
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
});
return await response.json();
}
catch (error) {
console.log('error : ' + error);
return error;

Load images from JSON object containing image references

I'm in the process of building an API that will take the JSON object output from a Konva stage and convert that into images on the server-side. I'm making use of the konva-node npm package and it works really well until it comes to loading in remote images that may have been a part of the original "design". I can see from this answer as to how we would solve the problem in the browser, however this doesn't appear to work in the same way in the nodejs implementation of Konva.
An example JSON input is the following:
let json = {
"attrs": {
"width": 600,
"height": 600
},
"className": "Stage",
"children": [{
"attrs": {},
"className": "Layer",
"children": [{
"attrs": {
"src": "https://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/1859A/production/_101883799_gettyimages-844211624.jpg"
},
"className": "Image"
}]
}, {
"attrs": {},
"className": "Layer",
"children": [{
"attrs": {
"text": "Hello world.",
"x": 50,
"y": 50,
"fontSize": 20,
"fill": "blue"
},
"className": "Text"
}]
}]
}
As you can see, I've subbed in src attributes as a sort of placeholder for when we come to load up the data into a canvas again.
The issue that I'm having is with actually getting those images to load in again once I process the JSON on the server-side.
Here is my current code
var fs = require('fs')
const Konva = require('konva-node')
var Request = require('pixl-request')
let json = {"attrs":{"width":600,"height":600},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"src":"https://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/1859A/production/_101883799_gettyimages-844211624.jpg"},"className":"Image"}]},{"attrs":{},"className":"Layer","children":[{"attrs":{"text":"Hello world.","x":50,"y":50,"fontSize":20,"fill":"blue"},"className":"Text"}]}] }
var stage = new Konva.Stage()
let loadedDesign = Konva.Node.create(json)
loadedDesign.find('Image').forEach((imageNode) => {
const imageURL = imageNode.getAttr('src')
var request = new Request();
request.get(imageURL, function(err, resp, data) {
var img = new Konva.window.Image()
img.onerror = err => { throw err }
img.onload = () => {
imageNode.image(img);
imageNode.getLayer().batchDraw();
}
img.src = data;
});
});
loadedDesign.toDataURL({
callback: function(data) {
var base64Data = data.replace(/^data:image\/png;base64,/, '');
fs.writeFile('./images/out.png', base64Data, 'base64', function(err) {
err && console.log(err)
console.log('See out.png')
});
}
});
The current output results in an image with the text on the canvas but the image never makes it in.
You need to load all images, only then use toDataURL(). I guess your image is not visible, because you convert stage to dataURL before images are loaded and rend
var request = new Request();
function loadImage(url) {
return new Promise(resolve => {
request.get(url, function(err, resp, data) {
var img = new Konva.window.Image();
img.onerror = err => {
throw err;
};
img.onload = () => {
resolve(img);
};
img.src = data;
});
});
}
async function run() {
const stage = Konva.Node.create(json);
const images = stage.find('Image');
for (const imageNode of images) {
const imageURL = imageNode.getAttr('src');
const img = await loadImage(imageURL);
imageNode.setImage(img);
}
stage.findOne('Layer').draw();
const data = stage.toDataURL();
var base64Data = data.replace(/^data:image\/png;base64,/, '');
fs.writeFile('out.png', base64Data, 'base64', function(err) {
err && console.log(err);
console.log('See out.png');
});
}
run().catch(e => {
console.error(e);
});

Ionic app image upload from camera / photo library

I'm working on a ionic chat app where the user can upload a photo as part of their message. I'm looking for a way to upload the image to my webhost server so I can retrieve it later via a URL.
The problem is that I'm not able to get it to upload to my web server.
I'm using these two plugins:
org.apache.cordova.file-transfer
cordova-plugin-camera
When I run the app in xcode simulator and select a picture from the device photolibrary, the console gives me the following messages:
File Transfer Finished with response code 200
void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode>
SUCCESS: ""
This is the code I currently use:
app.controller('HomeController', function($rootScope, $scope, $cordovaCamera, $ionicActionSheet, $cordovaFileTransfer){ ...
// open PhotoLibrary
$scope.openPhotoLibrary = function() {
var options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
//console.log(imageData);
//console.log(options);
var url = "http://mydomein.com/upload.php";
//target path may be local or url
var targetPath = imageData;
var filename = targetPath.split("/").pop();
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "image/jpg"
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
alert("success");
alert(JSON.stringify(result.response));
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
alert(JSON.stringify(err));
}, function (progress) {
// constant progress updates
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}, function(err) {
// error
console.log(err);
});
}
This is my upload.php file:
<?php
// move_uploaded_file($_FILES["file"]["tmp_name"], $cwd . '/files/images/');
move_uploaded_file($_FILES["file"]["tmp_name"], "/files/images");
?>
After some digging around and lot's of trying I finally got it working.
This is the code I came up with:
// open PhotoLibrary
$scope.openPhotoLibrary = function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
//console.log(imageData);
//console.log(options);
var image = document.getElementById('tempImage');
image.src = imageData;
var server = "http://yourdomain.com/upload.php",
filePath = imageData;
var date = new Date();
var options = {
fileKey: "file",
fileName: imageData.substr(imageData.lastIndexOf('/') + 1),
chunkedMode: false,
mimeType: "image/jpg"
};
$cordovaFileTransfer.upload(server, filePath, options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
console.log('Result_' + result.response[0] + '_ending');
alert("success");
alert(JSON.stringify(result.response));
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
//alert(JSON.stringify(err));
}, function (progress) {
// constant progress updates
});
}, function(err) {
// error
console.log(err);
});
}
And the code in upload.php on the domain server:
<?php
// if you want to find the root path of a folder use the line of code below:
//echo $_SERVER['DOCUMENT_ROOT']
if ($_FILES["file"]["error"] > 0){
echo "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Uploaded file: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kilobytes<br />";
if (file_exists("/files/".$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. No joke-- this error is almost <i><b>impossible</b></i> to get. Try again, I bet 1 million dollars it won't ever happen again.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/vhosts/yourdomain.com/subdomains/domainname/httpdocs/foldername/images/".$_FILES["file"]["name"]);
echo "Done";
}
}
?>
the app I am building for a company had the same issue, what we did is we just posted the image to our server as a base64 string. Then you can simple pull the string from the database and display it in a div. We used the NgCordova camera and then just pass in the data from the takePhoto function.
$scope.takePhoto = function () {
$ionicScrollDelegate.scrollTop();
console.log('fired camera');
$scope.uploadList = false;
$ionicPlatform.ready(function() {
var options = {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: false,
encodingType: Camera.EncodingType.PNG,
targetWidth: 800,
targetHeight: 1100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$ionicLoading.show({
template: 'Processing Image',
duration: 2000
});
$scope.image = "data:image/png;base64," + imageData;
if (ionic.Platform.isAndroid() === true) {
$scope.Data.Image = LZString.compressToUTF16($scope.image);
$scope.Data.isCompressed = 1;
} else {
$scope.Data.Image = $scope.image;
$scope.Data.isCompressed = 0;
}
if ($scope.tutorial) {
$scope.showAlert("Instructions: Step 3", '<div class="center">Now that you have taken a photo of the POD form, you must upload it to the server. Press the upload doc button in the bottom right of the screen.</div>');
}
$scope.on('')
}, function (err) {
console.log(err);
});
}, false);
};
$scope.UploadDoc = function () {
var req = {
method: 'POST',
url: ffService.baseUrlAuth + 'cc/upload',
headers: {
'x-access-token': ffService.token
},
data: $scope.Data
};
if ($scope.Data.Image === null || $scope.Data.Value === '') {
$scope.showAlert("Uh Oh!", '<div class="center">Please take a photo of your document before attempting an upload.</div>');
} else {
$http(req).success(function (data, status, headers, config) {
localStorage.setItem('tutorial', false);
$scope.tutorial = false;
$scope.getUploads($scope.PODOrder.OrderNo);
$scope.showAlert("Success!", '<div class="center">Your Document has been successfully uploaded!</div>');
$scope.uploadList = true;
}).error(function (data, status, headers, config) {
$rootScope.$broadcast('loading:hide');
$scope.showAlert("Something went wrong!", '<div class="center">Please make sure you have an internet connection and try again.</div>');
}).then(function(data, status, headers, config){
$scope.Data.Image = null;
});
}
};

Resources