Ionic - How to create Image Blob from cordovaImagePicker.getPictures ImagePicker for S3 - image

Using ionic,
I am trying to create an image blob from URI and have tried several codes but failed.
Here is where I implement the imagepicker in ionic:
$cordovaImagePicker.getPictures(options)
.then(function (results) {
console.log(results[0]);
var datablob = $scope.dataURItoBlob(results[0]);
technique 1 (create the blob):
$scope.dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
technique 2 (create the blob):
$scope.dataURItoBlob = function(dataURI) {
var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
Both techniques does not work. Please help! thank you very much.

$cordovaImagePicker.getPictures(options)
.then(function (results) {
console.log(results[0]);
dataURItoBlob(results[0], function(url){
var datablob = url;
}, function(error){
console.error(error);
})
})
function dataURItoBlob(path, cb, error) {
resolveLocalFileSystemURL(path, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
if (typeof cb === 'function') {
cb(this.result)
}
};
reader.readAsDataURL(file);
}, function (err) {
if (typeof error === 'function') {
error(err)
}
});
});
}
Needs to cordova-plugin-file

Related

sending and recieving files through RestBulider

controller on localhost:8000
const fs = require("fs");
exports.install = function () {
ROUTE("GET /", indexPage);
};
function indexPage() {
var self = this;
console.log(" In GET ROUTE");
RESTBuilder.GET("http://127.0.0.1:8500/getFile/").stream(function (
err,
response
) {
if (err) {
console.log(err);
return;
}
var writer = fs.createWriteStream("./public/testBuilder.txt");
// console.log("Writing to file");
response.pipe(writer);
self.json({ thankyou: "ok" });
});
}
controller on localhost:8500
exports.install = function () {
ROUTE("GET /getFile/", test);
};
function test() {
var self = this;
console.log("#################");
console.log(self.body);
self.file("~trimSail/restBuilder.txt");
// });
}
above code works in totaljs 3 but failing in total4.
sending a file in response to RestBuilder.GET and streaming the response to file.
error response.pipe is not a function.
First of all, please clean your code.
Total.js guidelines https://docs.totaljs.com/welcome/67b47001ty51c/
Optimized for Total.js:
const Fs = require('fs');
exports.install = function () {
ROUTE('GET /', index);
};
function index() {
var $ = this;
console.log('In GET ROUTE');
RESTBuilder.GET('http://127.0.0.1:8500/getFile/').stream($.successful(function(response) {
var writer = Fs.createWriteStream('./public/testBuilder.txt');
response.stream.pipe(writer);
$.json({ thankyou: 'ok' });
}));
}

Vue - DOM is not updating when doing .sort() on array

I am trying to sort some JSON data using Vue. The data gets changed when checking via Vue console debugger, but the actual DOM doesn't get updated.
This is my Vue code:
Array.prototype.unique = function () {
return this.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
};
if (!Array.prototype.last) {
Array.prototype.last = function () {
return this[this.length - 1];
};
};
var vm = new Vue({
el: "#streetleague-news",
data: {
allItems: [],
itemTypes: [],
itemTypesWithHeading: [],
selectedType: "All",
isActive: false,
sortDirection: "newFirst",
paginate: ['sortedItems']
},
created() {
axios.get("/umbraco/api/NewsLibraryApi/getall")
.then(response => {
// JSON responses are automatically parsed.
this.allItems = response.data;
this.itemTypes = this.allItems.filter(function (x) {
return x.Tag != null && x.Tag.length;
}).map(function (x) {
return x.Tag;
}).unique();
});
},
computed: {
isAllActive() {
return this.selectedType === "All";
},
filteredItems: function () {
var _this = this;
return _this.allItems.filter(function (x) {
return _this.selectedType === "All" || x.Tag === _this.selectedType;
});
},
sortedItems: function () {
var _this = this;
var news = _this.filteredItems;
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
return new Date(b.PostDate) - new Date(a.PostDate);
});
} else {
news.sort(function (a, b) {
return new Date(a.PostDate) - new Date(b.PostDate);
});
}
return news;
}
},
methods: {
onChangePage(sortedItems) {
// update page of items
this.sortedItems = sortedItems;
}
}
});
This is an HTML part:
<paginate class="grid-3 flex" name="sortedItems" :list="sortedItems" :per="12" ref="paginator">
<li class="flex" v-for="item in paginated('sortedItems')">
The bit that seems not to be working is the sortedItems: function () {....
Can anyone see why the DOM is not updating?
The most probable is that sort() method doesn't recognize Date object precedence. Use js timestamp instead:
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateB.valueOf() - dateA.valueOf();
});
} else {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateA.valueOf() - dateB.valueOf();
});
}
Got there eventually - thanks for your help
sortedItems: function () {
var _this = this;
var news = _this.allItems;
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateB.valueOf() - dateA.valueOf();
});
} else {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateA.valueOf() - dateB.valueOf();
})
}
return news.filter(x => {
return _this.selectedType === "All" || x.Tag ===
_this.selectedType;
});
}

Resize image and upload in couchdb or upload url blob to couchdb

I need to upload attached resized images into a couchdb doc. Right now I'm not resizing images, only uploading them by using the following code:
function attachFile(event) {
event.preventDefault();
var form_data = {};
$("form.attach-file :file").each(function() {
form_data[this.name] = this.value;
});
if (!form_data._attachments || form_data._attachments.length == 0) {
alert("Please select a file to upload.");
return;
}
var id = $("#ant-show").data("doc")._id;
$(this).ajaxSubmit({
url: "db/" + $.couch.encodeDocId(id),
success: function(resp) {
$('#modal-attach').modal("hide");
helios_link(id);
}
});
}
The code I'm using to rezise images, but that doesn't work to upload them, is the following:
function attachFile(event) {
function isImage (str) {
return str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);
}
function resizeAndUpload(file, callback, progress)
{
var reader = new FileReader();
reader.onloadend = function() {
var tempImg = new Image();
tempImg.onload = function() {
var MAX_WIDTH = 500;
var MAX_HEIGHT = 500;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var resizedCanvas = document.createElement('canvas');
resizedCanvas.width = tempW;
resizedCanvas.height = tempH;
var ctx = resizedCanvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = resizedCanvas.toDataURL("image/jpeg");
var file = dataURLtoBlob(dataURL);
var fd = $("#upload");
fd.append("_attachments", file);
var id = $("#ant-show").data("doc")._id;
console.log(fd);
fd.ajaxSubmit({
url: "db/" + $.couch.encodeDocId(id),
success: function(resp) {
$('#modal-attach').modal("hide");
helios_link(id);
}
});
};
tempImg.src = reader.result;
}
reader.readAsDataURL(file);
}
function dataURLtoBlob(dataURL) {
// Decodifica dataURL
var binary = atob(dataURL.split(',')[1]);
// Se transfiere a un array de 8-bit unsigned
var array = [];
var length = binary.length;
for(var i = 0; i < length; i++) {
array.push(binary.charCodeAt(i));
}
// Retorna el objeto Blob
return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}
function uploaded(response) {
// Código siguiente a la subida
}
function progressBar(percent) {
// Código durante la subida
}
event.preventDefault();
console.clear();
var files = document.getElementById('_attachments').files;
console.log(files);
resizeAndUpload(files[0], uploaded, progressBar);
}
Do anybody know how can I improve my code to make it work? I would like to have in fact two different solutions, one that helps me to improve my code and the second one, to get instructions on how to upload a URL BLOB as attachments into a couchdb document.

Not able to modify POST data in Firefox extension

I am trying to implement a Firefox Extension which modify the POST request data.
Code follows, it fails where marked "Fails here!!!"
Any insight would be helpful.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
var newData = "test 123";
function LOG(msg) {
var consoleService = Components.classes["#mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage(msg);
}
function CMP() {
this.registered = false;
this.register();
}
CMP.prototype = {
register: function() {
if (this.registered == false) {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "http-on-modify-request", false);
this.registered = true;
}
},
observe: function(subject, topic, data)
{
LOG("Inside observe");
if (topic == "http-on-modify-request")
{
LOG("TOPIC is http-on-modify-request");
var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
if(httpChannel.requestMethod == "POST"){
LOG("Inside POST")
var uploadChannel = httpChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
//var uploadChannelStream = uploadChannel.uploadStream;
Modify the data here. Here for testing i am passing "test 123" as new data
var newStringInputStream = Components.classes['#mozilla.org/io/string-input-stream;1'].createInstance(Components.interfaces.nsIStringInputStream);
newStringInputStream.setData(newData,newData.length);
LOG("set data in newStringInputStream!!");
uploadChannel.setUploadStream(newStringInputStream, "text/plain", -1 );// Fails here!!!
httpChannel.requestMethod = "POST";
LOG("upload DONE!!")
}
}
},
QueryInterface : function(aIID) {
if (aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsIObserver))
return this;
throw Components.results.NS_NOINTERFACE;
},
unregister: function() {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this, "http-on-modify-request");
},
classID: Components.ID('{F799F47E-ABA5-4AF1-B8F2-BD74E3E5BCC0}'),
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver])
};
if (XPCOMUtils.generateNSGetFactory)
{
var NSGetFactory = XPCOMUtils.generateNSGetFactory([CMP]);
}
Fixed it by changing by following in the above code. Main change was in setting modified data in httpChannel.uploadStream.
Hope this helps someone!
var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
if(httpChannel.requestMethod == "POST")
{
LOG("Inside POST")
var uploadChannel = httpChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
var newStringInputStream = Components.classes['#mozilla.org/io/string-input-stream;1'].createInstance(Components.interfaces.nsIStringInputStream);
newStringInputStream.setData(newData,newData.length);
var uploadChannelStream = uploadChannel.uploadStream;
uploadChannelStream = uploadChannelStream.QueryInterface(Components.interfaces.nsISeekableStream).seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
httpChannel.uploadStream.QueryInterface(Components.interfaces.nsIMIMEInputStream);
httpChannel.uploadStream.setData(newStringInputStream);
LOG("Done POST")
}

Why my model does not get synced?

I've written my first program with racer. It displays a simple text box manually bound to 'col.doc.prop' path. When I change the value, it does not apply to the store at server.
What causes my subscribed model not to get sync with server?
Server code:
var fs = require('fs');
var io = require('socket.io');
var racer = require('racer');
var mongo = require('racer-db-mongo');
racer.use(mongo);
racer.js({
entry: __dirname + '/client.js'
}, function(err, js) {
return fs.writeFileSync(__dirname + '/script.js', js);
});
var express = require('express');
var server = express.createServer();
server.use(express.static(__dirname));
server.get('/', function(req, res)
{
var model = store.createModel();
model.subscribe('col.doc', function(err, doc)
{
var prop = doc.get('prop');
if (!prop)
{
doc.set('prop', 123);
store.flush();
}
model.ref('_doc', doc);
model.bundle(function(bundle)
{
var client = require('fs').readFileSync('./client.html', 'utf-8');
client = client.replace('_init_', bundle.toString());
res.send(client);
});
});
});
var store = racer.createStore(
{
listen: server,
db:
{
type: 'Mongo',
uri: 'mongodb://localhost/racerdb'
}
});
store.set('col.doc.prop', 123);
store.flush();
server.listen(3001);
Client code:
useRacer = function()
{
var socket = io.connect('http://localhost:3001');
var racer = require('racer');
process.nextTick(function() {
racer.init(this.init, socket);
return delete this.init;
});
racer.on('ready', function(model)
{
addListener = document.addEventListener ? function(el, type, listener) {
return el.addEventListener(type, listener, false);
} : function(el, type, listener) {
return el.attachEvent('on' + type, function(e) {
return listener(e || event);
});
};
var element = document.getElementById('prop');
var listener = function()
{
var val = element.value;
model.set('col.doc.prop', val);
};
addListener(element, 'keyup', listener);
var upgrade = function(id, value)
{
if (model.connected)
{
var prop = model.get('col.doc.prop');
element.value = prop;
}
else
model.socket.socket.connect();
};
model.on('connectionStatus', upgrade);
model.on('set', 'con.*', upgrade);
});
};
The problem solved by changing some lines of the client code:
model.set('col.doc.prop', val) ==> model.set('_doc.prop', val)
model.get('col.doc.prop') ==> model.get('_doc.prop')
model.on('set', 'con.', upgrade) ==> model.on('set', '', upgrade)

Resources