Storing Image to remote server using Http Adapter - ibm-mobilefirst

I want to display Image and store Image on remote server.I am using Ibm Worklight Version 6.2.I Have gone through many links but didn't find the solution
My HTML Page code is
<fieldset style="height:auto;width:100% ">
<div id="Image" style="float:left;">
</div>
<div id ="delImage">
</div>
</fieldset>
and my Js Code is
uploadImage = function (){
navigator.camera.getPicture(onSuccessCallBack, onFailCallBack, {
quality: 50,
sourceType: Camera.PictureSourceType.CAMERA,
destinationType: Camera.DestinationType.FILE_URI
});
};
function onSuccessCallBack (imageData){
var img = document.createElement("img");
img.style.width = "60px";
img.style.height="60px";
img.src = imageData;
var Image = document.getElementById("Image");
Image.appendChild(img);
var delImg = document.createElement("img");
delImg.style.width = "60px";
delImg.style.height="60px";
delImg.src = "images/brws_gal.png";
var deleteImg = document.getElementById("delImage");
deleteImg.appendChild(delImg);
var invocationData = {
adapter : 'DisbursalRequestImageAdapter',
procedure : "uploadImageForDisbursal",
parameters : [ requestObject, sessionId, operationFlag,'','' ]
};
var options = {
timeout : timeout,
onSuccess : successCreateImg,
onFailure : failureCreateImg
};
WL.Client.invokeProcedure(invocationData, options);
};
Here, I am appending Dynamic Image in a div.
My Question is
I want to store the image to remote server using Http Adapter
I want to open the picture on the click of Picture.
I am not arrange the div vertically i.e. every time the photo is taken a new div should be created.

If you want to send an image to a remote server, you need to base64 encode the image and then send this string to be stored in the remote server's database.
If you want to then retrieve it you need to get the string and then decode the base64 string back to an image filetype and display the image in your HTML (the image should be stored in the device storage using Cordova APIs as you have demonstrated use of).
In fact, had you searched, the above is what you would've found in searches.

Related

Display an image when Blob is returned from an API

I’m writing a Vue app which uses the Microsoft Graph API and SDK for initial authentication on the front end and then uses different aspects of the API throughout the app. Like displaying emails, OneDrive files, etc.
I’m using the profile photo from a users Microsoft account to display an avatar to other users. My issue is that when I call {graphApi}/me/photo/$value the result returned is a Blob. This is the endpoint provided in MS Graph.
I’ve read the MS Graph docs thoroughly, combed MDN & other sources and have not found a way to transform this result into a simple image in my markup.
Template markup:
<template>
<img :src="userPhoto" :alt="user.displayName" />
</template>
Setup function logic:
<script setup>
import { client } from "./foobar"
const userPhoto = ref();
async function getPhoto(){
const photo = await client.api("/me/photo/$value").get()
console.log(photo.value)
userPhoto.value = photo
};
</script>
Returned result:
{Blob, image:{id: default, size:48x48}}
So how do I decode or download the Blob properly to display an image in my Vue markup?? I’ve tried createObjectURL and FileReader() without any luck. I’m sure there is a simple solution but I am not finding it. Thanks for the help.
Explanation:
In below snippet as you can see I am passing the objectId of the Employee fetched from Graph previously.
Then making call for employee to get their Avatar/DP
The Graph Profile Photo endpoint returns binary Data of the photo.
Convert that binary data into data:image/png;base64,<readAsDataURL> URL e.g. data:image/png;base64,iVBORw0KGgoAAAANSU...
Use in <img src="dataUrl"/>
let imageUrl = (await request.get(GRAPH_CONFIG.GRAPH_DP_ENDPT + objectId + "/photos/48x48/\$value", { responseType: 'arraybuffer', validateStatus: (status) => status === 200 || status === 404 }))
if (imageUrl.status === 200) {
let reader = new FileReader()
let blob = new Blob([imageUrl.data], {type: 'image/jpeg'})
reader.onload = (event) => {
return event.target?.result.toString();
}
reader.readAsDataURL(blob)
}

Show local image file:///tmp/someimage.jpg

Scenario
I'm contributing for a OSS project that is build on BlazorServerSide and ElectronNET.API Version 9.31.1.
In an Electron window we would like to show images from local storage UI via <img> tag.
What I have tried:
I have tried with:
<img src="file:///home/dani/pictures/someimage.jpg" />
But doesn't work. Image doesn't appear. I have then tried to create electron window with WebSecurity = false, but also doesn't help (images appears as broken on UI):
var browserWindowOptions = new BrowserWindowOptions
{
WebPreferences = new WebPreferences
{
WebSecurity = false,
},
};
Task.Run(async () => await Electron.WindowManager.CreateWindowAsync(
browserWindowOptions,
$"http://localhost:{BridgeSettings.WebPort}/Language/SetCultureByConfig"
));
Finally, as workaround, I'm sending the images as data base64 in img src's attribute, but it looks like a dirty approach.
My Question:
My question is, how can I show on electron window picture files from local storage.
Some irrelevant info:
The open source line where I need assistance.
There are several ways to go about this, so I will try to cover the most relevant use cases. Some of this depends on the context of your project.
Access to local files behave as cross origin requests by default. You could try using the crossorigin=anonymous attribute on your image tag, but doesn't work because your local file system will not be responding with cross origin headers.
Disabling the webSecurity option is a workaround, but is not recommended for security reasons, and will not usually work correctly anyway if your html is not also loaded from the local file system.
Disabling webSecurity will disable the same-origin policy and set allowRunningInsecureContent property to true. In other words, it allows the execution of insecure code from different domains.
https://www.electronjs.org/docs/tutorial/security#5-do-not-disable-websecurity
Here are some methods of working around this issue:
1 - Use the HTML5 File API to load local file resources and provide the ArrayBuffer to ImageData to write the image to a <canvas> .
function loadAsUrl(theFile) {
var reader = new FileReader();
var putCanvas = function(canvas_id) {
return function(loadedEvent) {
var buffer = new Uint8ClampedArray(loadedEvent.target.result);
document.getElementById(canvas_id)
.getContext('2d')
.putImageData(new ImageData(buffer, width, height), 0, 0);
}
}
reader.onload = putCanvas("canvas_id");
reader.readAsArrayBuffer(theFile);
}
1.b - It is also possible to load a file as a data URL. A data URL can be set as source (src) on img elements with JavaScript. Here is a JavaScript function named loadAsUrl() that shows how to load a file as a data URL using the HTML5 file API:
function loadAsUrl(theFile) {
var reader = new FileReader();
reader.onload = function(loadedEvent) {
var image = document.getElementById("theImage");
image.setAttribute("src", loadedEvent.target.result);
}
reader.readAsDataURL(theFile);
}
2 - Use the Node API fs to read the file, and convert it into a base64 encoded data url to embed in the image tag.
Hack - Alternatively you can try loading the image in a BrowserView or <webview>. The former overlays the content of your BrowserWindow while the latter is embedded into the content.
// In the main process.
const { BrowserView, BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
const view = new BrowserView()
win.setBrowserView(view)
view.setBounds({ x: 0, y: 0, width: 300, height: 300 })
view.webContents.loadURL('file:///home/dani/pictures/someimage.jpg')

Vuejs binding to img src only works on component rerender

I got a component that let's the user upload a profile picture with a preview before sending it off to cloudinary.
<template>
<div>
<div
class="image-input"
:style="{ 'background-image': `url(${person.personData.imagePreview})` } "
#click="chooseImage"
>
<span
v-if="!person.personData.imagePreview"
class="placeholder"
>
<i class="el-icon-plus avatar-uploader-icon"></i>
</span>
<input
type="file"
ref="fileInput"
#change="previewImage"
>
</div>
</div>
</template>
The methods to handle the preview:
chooseImage() {
this.$refs.fileInput.click()
},
previewImage(event) {
// Reference to the DOM input element
const input = event.target;
const files = input.files
console.log("File: ", input.files)
if (input.files && input.files[0]) {
this.person.personData.image = files[0];
const reader = new FileReader();
reader.onload = (e) => {
this.person.personData.imagePreview = e.target.result;
}
// Start the reader job - read file as a data url (base64 format)
reader.readAsDataURL(input.files[0]);
}
},
This works fine, except for when the user fetches a previous project from the DB. this.person.personData.imagePreview get's set to something like https://res.cloudinary.com/resumecloud/image/upload/.....id.jpg Then when the user wants to change his profile picture, he is able to select a new one from his local file system, and this.person.personData.imagePreview is read again as a data url with base64 format. But the preview doesn't work. Only when I change routes back and forth, the correct image selected by the user is displayed.
Like I said in the comment on my post. Turns out I'm an idiot. When displaying the preview, I used this.person.personData.imagePreview . When a user fetches a project from the DB, I just did this.person.personData = response.data. That works fine, apart from the fact that I had a different name for imagePreview on my backend. So I manually set it on the same load method when fetching from the DB like: this.person.personData.imagePreview = this.loadedPersonData.file. For some reason, that screwed with the reactivity of Vue.

Soundcloud e is null

I'm using the client side javascript SDK to connect to soundcloud.
now i want to block all latest tracks in a widget.
if i'm using SC.Widget('frameid') i'll get an error: Widget is not a function
so i have to implement the second script (widget api)
Whether I load the script directly from soundcloud or download it
I get the error: e is null
I tried to load the sdk before the widget api
and I also tried to load the api in document.ready but I still get the same error.
For selecting the iframe I tried to get it via ID and document.getElementbyId(..)
but that still did not work
Can someone tell me the solution?
what i'm doing wrong?
Looks like you dont reference the scripts in a proper way.
I hope this sketch points you in the right direction:
JS
(function() {
var iframe2 = document.querySelector('#widget2');
var widget2 = SC.Widget(iframe2);
var newurl = 'http://soundcloud.com/bnzlovesyou';
widget2.bind(SC.Widget.Events.READY, function() {
alert('ready');
widget2.bind(SC.Widget.Events.PLAY, function(eventData) {
alert('Playing..');
});
widget2.bind(SC.Widget.Events.PAUSE, function(eventData) {
alert('PAUSE..');
});
});
$( "#changetrack" ).click(function() {
widget2.load(newurl);
});
}());
HTML
<iframe id="widget2" width="100%" src = 'http://w.soundcloud.com/player/?url=http://soundcloud.com/barehouse_1'>
</iframe>
<div id="changetrack">Change Track / URL to my account ;)</div>
http://jsfiddle.net/iambnz/wpe2zmLh/

How to retrieve images from existing database using sql/http adapter from worklight application

I'm having an existing database and i have to show the list of images in my worklight application to user so that they can select and adds to cart.
The image column in database is having only path of images at server.
i.e "memory/toppings/nuts/hazelnuts.jpg"
"memory/toppings/nuts/macadamia_nuts.jpg"
so how to get all these images and show on my worklight application.
What you should do is concatenate the server URL and the image path after you retrieve it from the database.
Lets say in the database I store this: "/uploads/original/6/63935/1570735-master_chief.jpg", so the concatenation would be like this:
var url = "http://static.comicvine.com" + response.invocationResult.resultSet[0].profileimg;
$("#img1").attr("src", url);
Below is a working example.
Upon clicking a button, a SQL adapter procedure is invoked and returns a URL stored in the database. This URL is inserted into a pre-existing img tag's src attribute, which then gets displayed.
You need to take this implementation and alter it to fit your needs.
HTML:
<input type="button" value="insert image" onclick="getImageURL();"/><br>
<img id="img1" src=""/>
JS:
function getImageURL() {
var invocationData = {
adapter : 'retrieveImage',
procedure : 'retrieveImageURL',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : retrieveSuccess,
onFailure : retrieveFailure,
});
}
function retrieveSuccess(response) {
var url = "http://static.comicvine.com" + response.invocationResult.resultSet[0].profileimg;
$("#img1").attr("src", url);
}
function retrieveFailure() {
alert ("failure");
}
Alternate JS:
This code snippet shows how to add several images into dynamically created img tags.
function retrieveSuccess(response) {
var url, i;
for (i = 0; i < response.invocationResult.resultSet.length; i++) {
url = "http://static.comicvine.com" + response.invocationResult.resultSet[i].profileimg;
$("#imgholder").append("<li><img src='" + url + "'/></li>");
// imgholder is a UL in the HTML where the img tags will be appended to.
};
}
Adapter JS:
var procedure1Statement = WL.Server.createSQLStatement("select profileimg from users");
function retrieveImageURL() {
return WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement
});
}
Adapter XML:
<procedure name="retrieveImageURL"/>
In the database:
table (users)
|
-- column (profileimg)
------ row contents: some URL pointing to an image, for example: /myimg.png