Upload image to server angularjs - angularjs

I need to upload an image taken from my mobile device to my server. I found the angular-upload library to which makes reference. I need to do is to transform the image base 64, send it by post to my server because the server is where I will work with her. And the other, send from my server and work it from the application to run.
var server = URL_BASE+'addView/';
var trustAllHosts = true;
var ftOptions = new FileUploadOptions();
ftOptions.fileKey = 'file';
ftOptions.fileName = $scope.imagen.substr($scope.imagen.lastIndexOf('/') + 1);
ftOptions.mimeType = 'image/jpeg';
ftOptions.httpMethod = 'POST';
console.log(ftOptions);
$cordovaFileTransfer.upload(encodeURI(server), $scope.imagen, ftOptions, trustAllHosts)
.then(function(result) {
console.log(result)
}, function(err) {
// Error
console.log(err);
}, function (progress) {
});

ionic file transfer
I'm personally using Cordova file transfer for upload & download content from a server.
Base64 encoding
Don't know where is your image stored and how you retrieve it, but, either you specify that the image is base64 encode into the HTML file delimiter
OR
You transform your image using a canvas
See that post for more info : https://stackoverflow.com/a/20285053/3687474

You haven't specified what you really need so:
Here you have a factory
//Factory you register on your module
angular
.module('myApp')
.factory('sendBase64Image', sendBase64Image)
function sendBase64Image($http) {
var urlBase; //url to be filled in
var base64 = {};
base64.sendBase = function (baseImg) {
var request = $http({
method: "post",
url: urlBase,
headers: {
'Content-type': 'application/json'
},
data : baseImg
});
}
return base64;
}
You should then inject it via dependency injection to your controller and perform call to the server.
If you want to do something with a response use success() method to handle promise response.

Related

Passing External API to Angularjs

I'm working with an external API from Shipstation. I can do a GET request to pull the information in just fine into Nodejs, but I can't figure out how I can transfer that data client-side to manipulate within Angular? I've been struggling with this for a few days now and all my googling searching isn't helping out.
server.js
var express = require('express');
var request = require('request');
var app = express();
app.use(express.static('public'));
var Orders = require('./controllers/ordersController');
app.use('/orders', Orders);
app.listen(3000, function() {
console.log('I am live on port 3000');
});
ordersController.js
var request = require('request');
module.export = request({
method: 'GET',
url: 'https://ssapi.shipstation.com/orders/listbytag?orderStatus=awaiting_shipment&tagId=32099&page=1&pageSize=100',
headers: {
'Authorization': 'xxxxxxxxxxx'
}}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
});
I figured the best way was to put the GET request in its own "orders" module, export it, and then have angular access that route in an http request (/orders). Sounds good in theory, right?
I appreciate the help in advance! Thanks guys!
I'm assuming that the ShipStation API provides JSON which is easily consumable by Angular.
You can load the JSON into your Angular app like this:
$http.get('/orders:3000', function(data) {
$scope.Orders = data;
console.log($scope.Orders);
});
Add this to your controller, then check the browser's developer console to see the output. From there, you can manipulate the JSON object however you need and display the information in your HTML view.

Angular js, send ajax form data + image

I have a very simple form where users can write posts and insert a thunbnail image, the problem is that whenever i append the multipart header to the ajax request, the data doesn't get transmitted to the server. This is my ajax service:
angular.module('kadir.services', [])
.factory('cuService', function($q,$http) {
var newPost = function(data){
var deferrer = $q.defer();
$http({
method:"POST",
data:data,
headers:{'Content-Type': 'multipart/form-data'},
url:new_app_url}).then(function(res){
//success
deferrer.resolve(res.data);
},function(fail){
//fail
deferrer.reject(fail.data);
});
return deferrer.promise;
}
return {
newPost:newPost
}
});
I don't want to pull down any third party directives, i want to do this in plain angularjs (Unless i really really have to).

Render remote PNG image in AngularJS

I am developing an AngularJS application which displays a PNG image retrieved from a server.
If I put the URL (see below) in the browser I can see the image just fine. However, if I want to retrieve such image from my Angular application I cannot manage to display it (although I do receive the data!).
The JS code is the following:
$scope.receivedImage = null;
var url = 'https://subdomain.mydomain.uk/img?latitude=55.57&longitude=-5.16&extent=2000';
$http(
{
method: 'GET',
url: url,
headers: {
Accept: 'image/png'
}
}
).then(
function successCallback(response) {
var data = response.data;
$scope.receivedImage = data;
},
function errorCallback(response) {
console.error(response);
}
);
The problem is that I cannot see the image that is retrieved. To understand better the situation I put in the HTML page the following code:
<div ng-show="receivedImage">
<pre>{{receivedImage}}</pre>
<img data-ng-src="{{receivedImage}}" />
<img data-ng-src="data:image/png;{{receivedImage}}" />
</div>
The '' shows something like
�PNG IHDR�R9�%IDATx��̱ ������ �2��'��j�Z�V��w����LxIEND�B`�
The first '' does not show anything.
The second '' shows an image icon and throws in console an error:
GET
data:image/png;%EF%BF%BDPNG%1A%00%00%00IHDR%00%00%00%1E%00%00%00%1E%08%02%0…%BD%EF%BF%BD%EF%BF%BD%EF%BF%BDL%0E%17x%00%00%00%00IEND%EF%BF%BDB`%EF%BF%BD
net::ERR_INVALID_URL
How can I render this image correctly?
Try setting the ng-src attribute to a variable that is the url.
$scope.url = 'https://subdomain.mydomain.uk/img?latitude=55.57&longitude=-5.16&extent=2000';
and in the markup
<img ng-src="{{url}}" />
If the url is unprotected then the approach from Anthony helps a lot. For my use-case where the URL was protected i had to go with the below approach. In this case i had to inject the authentication headers by overriding angular's http authentication interceptors for accessing the protected URL.
// http call inside a service under a function named getImage()
$http(
{
method: 'GET',
url: 'YOUR_PROTECTED_RESOURCE_URL',
// This is required for getting your data as buffer array
{
responseType: 'arraybuffer'
}
}
).then(
function successCallback(response) {
return response;
},
function errorCallback(response) {
console.error(response);
}
);
Inside your controller or directive the data that comes from the above call has to be handled like so:
// Function to get the image from the server
var handleImage = function(){
MyHttpService.getImage()
.then(function(response){
// Can be used within ng-src fro displaying image
$scope.receivedImage = 'data:image/png;base64,'+_arrayBufferToBase64(response);
}, function(error){
console.error(error);
});
};
// Convert the buffer to base64
var _arrayBufferToBase64 = function( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
console.log(len);
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
};
Hope this helps someone who is trying to access the resource from a protected resource URI.

How to return image from $http.get in AngularJS

In my controller I call a service that returns a promise
var onComplete = function(data) {
$scope.myImage = data;
};
In my service I make a call to get the image by passing url directly to the image itself:
return $http.get("http://someurl.com/someimagepath")
.then(function(response){
return response.data;
});
All the calls are succeeding and the response.data appears to be holding in an image inside:
����JFIF��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90
��C

��C
����"��
���}!1AQa"q2���#B��R��$
although I'm not sure if it actually does because I'm having trouble displaying it. I've tried (inside index.html)
<img ng-src="{{myImage}}">
and
<img ng-src="{{myImage}}.jpeg">
and
<img ng-src="data:image/JPEG;base64,{{myImage}}">
Ideas?
Is it possible to return an actual image from $http.get and convert its response back to image (jpeg, etc.)
Thanks!
None of the methods seems to be complete, this is a complete solution:
$http({
method: 'GET',
url: imageUrl,
responseType: 'arraybuffer'
}).then(function(response) {
console.log(response);
var str = _arrayBufferToBase64(response.data);
console.log(str);
// str is base64 encoded.
}, function(response) {
console.error('error in getting static img.');
});
function _arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
Then I am able to use it directly:
<img data-ng-src="data:image/png;base64,{{img}}">
The function to convert arraybuffer into base64 is directly taken from ArrayBuffer to base64 encoded string
Just in case anyone needs it.
In my case, I had to send the request through angular's $http service, because of various transformers and other fancy stuff we do with it.
So based on the Mozilla's guide mentioned earlier, I came up with the following solution:
let getImageDataURL = (url, imageType = 'image/jpeg') => {
return $http.get(url, {responseType: 'arraybuffer'}).then((res) => {
let blob = new Blob([res.data], {type: imageType});
return (window.URL || window.webkitURL).createObjectURL(blob);
});
};
The basic idea is to set the responseType property of the underlying XHR request and the convert the binary content to data URL.
The image that's coming back is in binary encoding, rather than Base64.
Understandably, <img> tags don't support sourcing from binary through attributes, so you'll have to look at another solution.
You could try converting the binary encoding to Base64 at the client side using TypedArrays together with the btoa function. Then you'd be able to use
<img ng-src="data:image/JPEG;base64,{{myImage}}">
This guide a by Mozilla covers making an XHR request for and image and reading it directly into a UInt8Array. It should be a good starting place.
It's written for plain old Javascript, but translating it to Angular should be a good exercise if you are just learning the ropes.
By way of https://stackoverflow.com/a/43032560/418819, you can use "blob" as the responseType and very neatly get the data url with a FileReader.
$http.get( url, { responseType: "blob" } ).then((result) => {
var reader = new FileReader();
reader.readAsDataURL( result.data );
reader.onload = function (e) {
return e.target.result;
};
});
You can reference it like so:
<img data-ng-src="{{img}}">

Outputting a PDF (created with FPDF) in AngularJS

I am using FPDF to create a PDF on a Laravel backend that serves Angular. I have created it in the normal FPDF way and I am unsure how to send the file response back to Angular.
I read here about generall how to go about it by configuring my $http request as below:
return $http({url: '/api/print/class-list', method: "POST", data: {data: data}, headers: {'Accept':'application/pdf'}, responseType: 'arrayBuffer'})
.then(function(response)
{
console.log(response.data);
var file = new Blob([response.data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
var content = $sce.trustAsResourceUrl(fileURL);
return content;
}
I have injected $sce in the service and i am outputting the content in an embed tag. The tag just shows an empty PDF. I am wondering what the problem could be. Also, on the Laravel side, once I am done creating the PDF by writing $pdf->Output("page","D"), is there a way i should write return something so that it can be returned to Angular?
Also, when i console response, it kindof returns blob or some pdf stuff, and a number of errors after that like:
"Warning: Unsupported feature "unknown"

Resources