Ionic Upload Image to Server - ionic-framework

I need to upload captured image and album image to the server in ionic app.
Is anyone know how to do that?
I am just fresh in developing ionic app

It is not really clear what you mean by uploading an image to the server with an ionic app.
A suggestion might be to convert the image to a Base64 string and send it to the server.

i am using cordova imagepicker(pick image from camera) and upload to s3 server.
function getImageFromGallery(cb) {
// console.log('getImageFromGallery');
var options = {
maximumImagesCount: 1,
width: 1280, //width of image
height: 1280, // height of image
quality: 80
};
$cordovaImagePicker.getPictures(options)
.then(function(results) {
console.log(results);
}, function(error) {
alert(error);
});
}
function uploadImage(imageDataURI) {
// console.log('uploadImage');
var fileURL = imageDataURI;
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.chunkedMode = true;
options.method = 'POST';
var params = {
'image_type': 'food'
};
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://xxx.in/api/upload_image"),
viewUploadedPictures,
function(error) {
console.log(error);
}, options);
console.log('success');
}
var viewUploadedPictures = function(response) {
var res = response.response;
var jres = JSON.parse(res);
var imgUrl = jres.data.public_photo_url;
console.log('new image url link', imgUrl);
}
Note:- i am using REST api for image uploading "http://xxx.in/api/upload_image"
* * Dependency Injection $upload* *

Related

Images Drawn by the canvas Component Cannot Be Displayed in the Album

After an image drawn by the canvas component is saved to the album, the image cannot be displayed in the album. Only a black background image is displayed. How Do I Ensure that Pictures Are Normal After Being Saved to the Album?
Huawei Quick App Center creates a ctx object each time when it calls the getContextmethod, and therefore different ctx objects will be returned. Some of these ctx objects are empty. An empty ctx object may be obtained in a random selection. As a result, the image saved may have no content. The code is as follows:
Code for using canvas to draw an image:
pic() {
var test = this.$element("canvas");
var ctx = test.getContext("2d");
var img = new Image();
img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
img.onload = function () {
console.log("Image loaded successfully");
ctx.drawImage(img, 10, 10, 300, 300, );
}
img.onerror = function () {
console.log("Failed to load the image");
}
},
Code for saving the image:
save() {
var test = this.$element("canvas");
test.toTempFilePath({
fileType: "jpg",
quality: 1.0,
success: (data) => {
console.log(`Canvas toTempFilePath success ${data.uri}`)
console.log(`Canvas toTempFilePath success ${data.tempFilePath}`)
media.saveToPhotosAlbum({
uri: data.uri,
success: function (ret) {
console.log("save success: ");
},
fail: function (data, code) {
console.log("handling fail, code=" + code);
}
})
},
fail: (data) => {
console.log('Canvas toTempFilePath data =' + data);
},
complete: () => {
console.log('Canvas toTempFilePath complete.');
}
})
}
Solution
Define ctx as a global variable and check whether it is empty. Assign an initial value to an empty ctx.
Optimized code:
var ctx; // Define a global variable.
pic() {
if (!ctx) {// Check whether a ctx object is empty. If it is empty, assign the 2d value to it.
var test = this.$element("canvas");
var tt = test.getContext("2d");
ctx = tt;
}
var img = new Image();
img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
img.onload = function () {
console.log("Image loaded successfully");
ctx.drawImage(img, 10, 10, 300, 300, );
}
img.onerror = function () {
console.log("Failed to load the image");
}
}

Uploading a file using the File Uploader module

I am trying to upload a file using the FileUploader module in SAPUI5. The code I am trying to follow is from a blog https://blogs.sap.com/2016/11/08/step-by-step-on-how-to-use-the-sapui5-file-upload-feature/ however the code does not seem to execute the reader.onload function? It gets to reader.readAsDataURL(file) and dose not do anything? I am not sure where the problem lies and how to get it to work? Hekp will be much appreciated, there is a similar issue in the blog response but no help has been given.
XML
<u:FileUploader
id="VRCFileUploader"
value="{VRCFileUpload}"
placeholder="Please Attach document"
fileType="jpg,png,pdf"
style="Emphasized"
useMultipart="false" >
</u:FileUploader>
JS
function upload(evnt) {
var token;
var oView = this.getView();
var oFileUploader = this.byId("VRCFileUploader");
var sFileName = oFileUploader.getValue();
if (sFileName === "") {
sap.m.MessageToast.show("Please select a File to Upload");
return;
}
var file = jQuery.sap.domById(oFileUploader.getId() + "-fu").files[0];
var base64_marker = "data:" + file.type + ";base64,";
var reader = new FileReader();
//on load
reader.onLoad = (function(theFile){
return function(evt) {
//locate base64 content
var base64Index = evt.target.result.indexOf(base64_marker) + base64_marker.lenght;
// get base64 content
var base64 = evt.target.result.substring(base64Index);
var sTasksService = "SOME URL";
var sService2 = "SOME URL";
var oViewModel = oView.getModel();
var oContext = oView.getBindingContext();
var oTask = oViewModel.getProperty(oContext.getPath());
var oDataModel = sap.ui.getCore.getModel();
var sWorkitemId = JSON.stringify(oTask.wiId);
var service_url = sService2;
$.ajaxsetup({
cache: false
});
jQuery.ajax({
url: service_url,
asyn: false,
datatype: "json",
cache: false,
data: base64,
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader("x-csrf-Token", token);
xhr.setRequestHeader("content-Type", file.type);
xhr.setRequestHeader("slug", sFileName);
xhr.setRequestHeader("WorkitemId", oTask.WiId);
},
success: function(odata) {
sap.m.MessageToast.show("file successfully uploaded");
oFileUploader.setValue("");
},
error: function(odata) {
sap.m.MessageToast.show("file Upload error");
}
});
};
})(file);
//Read file
reader.readAsDataURL(file);
}
In reply to Vortex:
Why is there an IIFE on the method being used on the onLoad Property?
Try to do somenthing like this:
reader.onload = event => {
let fileAsDataUrl = event.target.result;
....
};

upload base64 image facebook graph api how to use this script

Upload Base64 Image Facebook Graph API
i want to use this script that link is attached how i can use this in my wordpress post?
i want to use this for fbcover photo site.
Take a look at this code I hacked together from various examples - you can use this to post a pure base64 string to the Facebook API - no server side processing.
Here's a demo: http://rocky-plains-2911.herokuapp.com/
This javascript handles the converting of a HTML5 Canvas element to base64 and using the Facebook API to post the image string
<script type = "text/javascript">
// Post a BASE64 Encoded PNG Image to facebook
function PostImageToFacebook(authToken) {
var canvas = document.getElementById("c");
var imageData = canvas.toDataURL("image/png");
try {
blob = dataURItoBlob(imageData);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", authToken);
fd.append("source", blob);
fd.append("message", "Photo Text");
try {
$.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + authToken,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data);
$("#poster").html("Posted Canvas Successfully");
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
console.log("Posted to facebook");
}
});
} catch (e) {
console.log(e);
}
}
// Convert a data URI to blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
</script>
This handles the Facebook Authentication and shows basic HTML setup
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
cache: true
});
$.getScript('//connect.facebook.net/en_UK/all.js', function () {
// Load the APP / SDK
FB.init({
appId: '288585397909199', // App ID from the App Dashboard
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true, // parse XFBML tags on this page?
frictionlessRequests: true,
oauth: true
});
FB.login(function (response) {
if (response.authResponse) {
window.authToken = response.authResponse.accessToken;
} else {
}
}, {
scope: 'publish_actions,publish_stream'
});
});
// Populate the canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("This will be posted to Facebook as an image", 10, 50);
});
</script>
<div id="fb-root"></div>
<canvas id="c" width="500" height="500"></canvas>
<a id="poster" href="#" onclick="PostImageToFacebook(window.authToken)">Post Canvas Image To Facebook</a>
I needed this too, and was not happy with all the code around it because it is lengthy and usually needs jQuery. Here is my code for uploading from Canvas to Facebook:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
const upload = async (response) => {
let canvas = document.getElementById('canvas');
let dataURL = canvas.toDataURL('image/jpeg', 1.0);
let blob = dataURItoBlob(dataURL);
let formData = new FormData();
formData.append('access_token', response.authResponse.accessToken);
formData.append('source', blob);
let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
body: formData,
method: 'post'
});
responseFB = await responseFB.json();
console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
FB.login((response) => {
//TODO check if user is logged in and authorized publish_actions
upload(response);
}, {scope: 'publish_actions'})
})
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/

How to insert a blob into mongodb in meteor

I am using Recorder.js, which allows you to display an audio recording like so
recorder.exportWAV(function(blob) {
var url = URL.createObjectURL(blob);
var au = document.createElement('audio');
au.controls = true;
au.src = url;
}
But how can I save the blob to the database? Assuming I have a Recordings collection:
recorder.exportWAV(function(blob) {
Recordings.insert({data: blob});
}
will only store this
{data: { "type" : "audio/wav", "size" : 704556 }}
which does not have the actual content.
After watching the file upload episode from eventedmind.com, it turns out the way to do it is to use the FileReader to read a blob as ArrayBuffer, which is then converted to Uint8Array to be stored in mongo:
var BinaryFileReader = {
read: function(file, callback){
var reader = new FileReader;
var fileInfo = {
name: file.name,
type: file.type,
size: file.size,
file: null
}
reader.onload = function(){
fileInfo.file = new Uint8Array(reader.result);
callback(null, fileInfo);
}
reader.onerror = function(){
callback(reader.error);
}
reader.readAsArrayBuffer(file);
}
}
The exportWAV callback is then
recorder.exportWAV(function(blob) {
BinaryFileReader.read(blob, function(err, fileInfo){
Recordings.insert(fileInfo)
});
});
Then I can display one of my recordings by:
Deps.autorun(function(){
var rec = Recordings.findOne();
if (rec){
var au = document.createElement('audio');
au.controls = true;
var blob = new Blob([rec.file],{type: rec.type});
au.src = URL.createObjectURL(blob);
document.getElementById("recordingslist").appendChild(au);
}
})
I don't know if the previous snippet works in other browsers, but this may:
var base64Data = btoa(String.fromCharCode.apply(null, rec.file))
var au = document.createElement('audio');
au.controls = true;
au.src = "data:"+rec.type+";base64,"+base64Data
Just in case, did you notice this line in their example
Make sure you are using a recent version of Google Chrome, at the
moment this only works with Google Chrome Canary.
I will soon need to look into this for my own project, hope you get it running.

How to download images from a site with phantomjs

I wanna save some images from a site. At the moment I can get the paths to the images but I have no clue how to get and save the images with phantomJs.
findRotationTeaserImages = ->
paths = page.evaluate ->
jQuery('.rotate img').map(-> return this.src).get()
for path, i in paths
console.log(path);
//save the image
I know this is an old question, but you do this pretty simply by storing the dimensions and location of each image on the in an object, then altering the phantomjs page.clipRect so that the page.render() method renders only the area where the image is. Here is an example, scraping multiple images from http://dribbble.com/ :
var page = require('webpage').create();
page.open('http://dribbble.com/', function() {
page.includeJs('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',function() {
var images = page.evaluate(function() {
var images = [];
function getImgDimensions($i) {
return {
top : $i.offset().top,
left : $i.offset().left,
width : $i.width(),
height : $i.height()
}
}
$('.dribbble-img img').each(function() {
var img = getImgDimensions($(this));
images.push(img);
});
return images;
});
images.forEach(function(imageObj, index, array){
page.clipRect = imageObj;
page.render('images/'+index+'.png')
});
phantom.exit();
});
});
There is now another way to do this.
var fs = require("fs");
var imageBase64 = page.evaluate(function(){
var canvas = document.createElement("canvas");
canvas.width =img.width;
canvas.height =img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL ("image/png").split(",")[1];
})
fs.write("file.png",atob(imageBase64),'wb');
Solve this by starting a child process running a node script that download the images:
phantomJs script:
findRotationTeaserImages = ->
paths = page.evaluate ->
jQuery('.rotate img').map(-> return this.src).get()
args = ('loadRotationTeaser.js ' + paths.join(' ')).split(' ')
child_process.execFile("node", args, null, (err, stdout, stderr) ->
phantom.exit()
)
nodeJs script
http = require('http-get');
args = process.argv.splice(2)
for path, i in args
http.get path, 'public/images/rotationTeaser/img' + i + '.jpeg', (error, result) ->
In case image dimensions are known:
var webPage = require('webpage');
/**
* Download image with known dimension.
* #param src Image source
* #param dest Destination full path
* #param width Image width
* #param height Image height
* #param timeout Operation timeout
* #param cbk Callback (optional)
* #param cbkParam Parameter to pass back to the callback (optional)
*/
function downloadImg(src, dest, width, height, timeout, cbk, cbkParam) {
var page = webPage.create();
page.settings.resourceTimeout = timeout; //resources loading timeout(ms)
page.settings.webSecurityEnabled = false; //Disable web security
page.settings.XSSAuditingEnabled = false; //Disable web security
page.open(src, function(status) {
// missing images sometime receive text from server
var success = status == 'success' && !page.plainText;
if (success) {
page.clipRect = {
top: 0,
left: 0,
width: width,
height: height
};
page.render(dest);
}
cbk && cbk(success, cbkParam);
page.close();
});
};
I've experienced really a lot troubles when using the render method. Luckily I finally come up with two better solution. Here is the code I used in my project. First solution has some trouble to update the cookie, so it cannot work well when fetching captcha image. Both method will cause a new http request. But with a few modifications, the second one can ommit such kind of request.
The first one fetches the cookie from phantomJs and makes a new http request using request. The second one uses base64 to pass the image.
async download(download_url, stream) {
logger.profile(`download(download_url='${download_url}')`);
let orig_url = await this.page.property('url');
download_url = url.resolve(orig_url, download_url);
let cookies = await this.page.property('cookies');
let jar = request.jar();
for (let cookie of cookies) {
if (cookie.name !== undefined) {
cookie.key = cookie.name;
delete cookie.name;
}
if (cookie.httponly !== undefined) {
cookie.httpOnly = cookie.httponly;
delete cookie.httponly;
}
if (cookie.expires !== undefined)
cookie.expires = new Date(cookie.expires);
jar.setCookie(new Cookie(cookie), download_url, {ignoreError: true});
}
let req = request({
url: download_url,
jar: jar,
headers: {
'User-Agent': this.user_agent,
'Referer': orig_url
}
});
await new Promise((resolve, reject) => {
req.pipe(stream)
.on('close', resolve)
.on('error', reject);
});
// Due to this issue https://github.com/ariya/phantomjs/issues/13409, we cannot set cookies back
// to browser. It is said to be redesigned, but till now (Mar 31 2017), no change has been made.
/*await Promise.all([
new Promise((resolve, reject) => {
req.on('response', () => {
jar._jar.store.getAllCookies((err, cookies) => {
if (err) {
reject(err);
return;
}
cookies = cookies.map(x => x.toJSON());
for (let cookie of cookies) {
if (cookie.key !== undefined) {
cookie.name = cookie.key;
delete cookie.key;
}
if (cookie.httpOnly !== undefined) {
cookie.httponly = cookie.httpOnly;
delete cookie.httpOnly;
}
if (cookie.expires instanceof Date) {
cookie.expires = cookie.expires.toGMTString();
cookie.expiry = cookie.expires.toTime();
}
else if (cookie.expires == Infinity)
delete cookie.expires;
delete cookie.lastAccessed;
delete cookie.creation;
delete cookie.hostOnly;
}
this.page.property('cookies', cookies).then(resolve).catch(reject);
});
}).on('error', reject);
}),
new Promise((resolve, reject) => {
req.pipe(fs.createWriteStream(save_path))
.on('close', resolve)
.on('error', reject);
})
]);*/
logger.profile(`download(download_url='${download_url}')`);
}
async download_image(download_url, stream) {
logger.profile(`download_image(download_url='${download_url}')`);
await Promise.all([
new Promise((resolve, reject) => {
this.client.once('donwload image', data => {
if (data.err)
reject(err);
else
stream.write(Buffer.from(data.data, 'base64'), resolve);
});
}),
this.page.evaluate(function (url) {
var img = new Image(), callback = function (err, data) {
callPhantom({
event: 'donwload image',
data: {
err: err && err.message,
data: data
}
});
};
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0);
callback(null, canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.onerror = function () {
callback(new Error('Failed to fetch image.'));
};
img.src = url;
}, download_url)
]);
logger.profile(`download_image(download_url='${download_url}')`);
}