How can I get the signature from Vue Signature Pad + Laravel - laravel

Hi I have read but I have not found the answer so I ask:
How can I get the signature picture?
My Vuejs code is this one:
<VueSignaturePad width="100%" height="500px" ref="signaturePad" />
<div>
<button #click="save">Guardar</button>
<button #click="undo">Borrar</button>
</div>
My methods are:
undo() {
this.$refs.signaturePad.undoSignature();
},
save() {
this.loading = true;
e.preventDefault();
let currentObj = this;
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
let formData = new FormData();
formData.append('signature', this.$refs.signaturePad.saveSignature());
axios.post('/api/signature/store?api_token='+App.apiToken, formData, config)
.then(function (response) {
currentObj.success = response.data.success;
})
}
My Laravel code has this:
$fileName = time().'_'.'signature'.'_'.$this->user->rut.'_'.date('d_m_Y').'.'.$request->file->getClientOriginalExtension();
$signature = new Signature;
$signature->rut = $this->user->rut;
$signature->signature = $fileName;
$signature->save();
Storage::disk('dropbox')->putFileAs(
'signatures/',
$request->file,
$fileName
);
The problem is that it displays me an error:
Call to a member function getClientOriginalExtension() on null
So I wonder how can I get the image?

this option worked for me to convert the base64 file to image before sending it
Vue code
<div id="app">
<vueSignature ref="signature" :sigOption="option" :w="'800px'" :h="'400px'" :disabled="disabled"></vueSignature>
<vueSignature ref="signature1" :sigOption="option"></vueSignature>
<button #click="save">Save</button>
<button #click="clear">Clear</button>
<button #click="handleDisabled">disabled</button>
</div>
functions
save(){
var _this = this;
var png = _this.$refs.signature.save()
var block = png.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];// In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."
// Convert it to a blob to upload
var blob = this.b64toBlob(realData, contentType);
let data = new FormData()
data.append('img', blob)
axios.post(this.url, data).then(res=>{
console.log(res.data)
}).catch(function (error) {
console.log(error.response)
})
},
b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
},
I hope I've helped

Related

Binding Images to Image placeholder in repeater

I have a repeater that loads info from SQLite and works well. The user has options to take photos which are stored both in their photo library and in a temp folder. On reloading the page I need to reload the images to for a sliding gallery of thumbnails under the relevant section in the repeater.
The Image repeater is defined as
<Repeater items="{{ images }}" id="{{ repeaterphotoid }}">
<Repeater.itemTemplate>
<Image src="{{localurl}}" width="75" height="75" visibility="{{photoevidence === 'y' ? 'visible' : 'collapse'}}" />
</Repeater.itemTemplate>
</Repeater>
And my code is
exports.takePic = function(args){
var page = args.object;
camera.requestPermissions().then(
function success(){
var livesite = appSettings.getString("livesite");
var images=[];
var whichcamera = args.object;
var options = {saveToGallery: true, keepAspectRation: true, height: 1024 };
var gallery = args.object.page.getViewById("images-"+whichcamera.id);
var source = new imageSourceModule.ImageSource();
camera.takePicture(options).then(function(imageAsset){
var img = new imageModule.Image();
source.fromAsset(imageAsset).then((imageSource) => {
var auditDB = new sqlite("my.db", function(err, db){
if (err){
alert("Failed to open the database", err);
} else {
var tempfilename = livesite+"-"+whichcamera.qid+"-";
db.all("SELECT filename FROM images WHERE filename LIKE '"+tempfilename+"%'").then(rows =>{
//console.log("Images rows="+rows.length+1);
if (rows.length == 0){
imageCount = 1;
}
else
{
imageCount = rows.length+1;
}
var livesite = appSettings.getString("livesite");
// var path = filesystem.path.join(filesystem.knownFolders.documants().path,"photos")
var folder = filesystem.knownFolders.documents();
var filename = livesite+"-"+whichcamera.qid+"-"+imageCount+".jpg";
var imgPath = filesystem.path.join(folder.path,filename);
var saved = imageSource.saveToFile(imgPath,"jpg");
if (saved){
var livesite = appSettings.getString("livesite");
var liveaudit = appSettings.getString("liveaudit");
db.execSQL("INSERT INTO images (localurl,remoteurl,syncd,siteid,filename,question) VALUES(?,?,?,?,?,?)",[imgPath,'-','n',livesite,filename,whichcamera.qid])
var imageList = [];
var tempfilename = livesite+"-"+whichcamera.qid+"-";
var imageSQL = "SELECT localurl,remoteurl,filename FROM images WHERE filename LIKE '"+tempfilename+"%'";
db.all(imageSQL).then(rows =>{
for (var row in rows) {
imageList.push({
localurl: rows[row][0],
filename: rows[row][2]
});
}
const imagesource = fromObject({
images: imageList
});
imagesource.set = ("images", imageList);
var imageholder = args.object.page.getViewById("repeat_"+whichcamera.id);
imageholder.bindingContext = imagesource;
});
};
});
};
});
});
}).catch(function (err) {
alert("Camera Error "+err.message);
})
//alert("Taking Pic with camera "+whichcamera.id);
},
function failure(){
alert("You must allow this app access to the camera and your photos library.")
});
}
Binding to the questions works as expected but I cannot bind the images to the image repeater, nothing happens. Obviously missing something but going code blind.

Pass image through ajax using cordova

I am developing my mobile application using ionic framework and I want it to connect to my API through ajax. Currenty, in the mobile side, which is I am using Ionic Framework, I want to upload an image and pass it to my api through ajax. I am using Cordova for the upload but it seems it doesn't found the URL I indicated.
Here's the HTML
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button>
</div>
</ion-footer-bar>
Here's the uploadImage() function in the controller (Just copied the code in a site. Forgot where) EDIT: added targetPath
$scope.uploadImage = function() {
// Destination URL
var url = "http://192.168.0.19/identificare_api/public/api/plants/image";
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
var jsonparse = JSON.parse(result);
$scope.showAlert(jsonparse);
}
But in the upload part, I want to do it in ajax to indicate the method for the URL but the problem I don't know what put in data.
$.ajax({
url: "http://192.168.0.19/identificare_api/public/api/plants/image",
type: 'POST',
data:
success:function(json){
var jsonparse = JSON.parse(json);
alert(jsonparse);
},
error:function(){
alert("Error");
}
});
Can someone help me with this issue?
UPDATE: Applied here #Blauharley's comment below
I had another issue here. I returned the $_FILES['image']['tmp_name'] in the API side but it returns nothing but when I returned the $_FILES['image']['name'], it returned my_image.jpg. Why it doesn't have tmp_name?
$scope.uploadImage = function() {
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
$scope.getBase64ImageByURL(targetPath).then(function(base64Image){
var blob = $scope.base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('image', blob, "my_image.jpg");
fd.append('user_token', "rLUrh37rfTozuBxmemHtlKMgH");
$.ajax({
url: 'http://192.168.0.19/identificare_api/public/api/plants/image',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success:function(res){
alert(res);
},
error:function(err){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
};
$scope.getBase64ImageByURL = function(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
};
$scope.base64ToBlob = function(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
};
ADDED: API side
public function image(){
echo json_encode($_FILES['image']['tmp_name']);
}

Nativescript - How to POST Image with http.request

Help, I need call the http.request for send Image captured in camera api in my NativeScript App.
I capture the photo in camera api for nativescript and need send to api in upload process.
Follow the code about this process:
var frameModule = require("ui/frame");
var viewModule = require("ui/core/view");
var Observable = require("data/observable").Observable;
var config = require("../../shared/config");
var cameraModule = require("camera");
var imageModule = require("ui/image");
var http = require("http");
exports.loaded = function(args) {
var page = args.object;
viewModel = new Observable({
coleta: config.id_coleta
});
page.bindingContext = viewModel;
};
exports.voltar = function() {
var topmost = frameModule.topmost();
topmost.navigate("views/ocorrencia/menuocorrencia");
};
function tapFoto() {
cameraModule.takePicture({
width: 300,
height: 300,
keepAspectRatio: true
}).then(function(picture) {
var image = new imageModule.Image();
image.imageSource = picture;
var item = {
itemImage: picture
};
var urlfoto = "http://192.1.1.1:8090/sendphoto/upload";
alert("URL: " + urlfoto);
http.request({
url: urlfoto,
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
content: ({uploadFile: image.imageSource, entrega: config.id_coleta})
}).then(function (response) {
var statusCode = response.statusCode;
alert("Codigo Retorno: " + statusCode);
alert("Foto registrada com sucesso.");
}, function (e){
alert("Erro: " + e);
});
});
}
exports.tapFoto = tapFoto;
I recommend using of nativescript-background-http plugin for uploading files.
tns plugin add nativescript-background-http
Here is your code modifed to work with the installed plugin:
"use strict";
var Observable = require("data/observable").Observable;
var cameraModule = require("camera");
var fs = require("file-system");
var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");
var viewModel = new Observable();
function navigatingTo(args) {
var page = args.object;
page.bindingContext = viewModel;
}
exports.navigatingTo = navigatingTo;
function onTap() {
cameraModule.takePicture({
width: 300,
height: 300,
keepAspectRatio: true
}).then(function (imageSource) {
console.log("Image taken!");
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = imageSource.saveToFile(path, "png");
var request = {
url: "http://httpbin.org/post",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": "Test.png"
},
description: "{ 'uploading': " + "Test.png" + " }"
};
var task = session.uploadFile(path, request);
task.on("progress", logEvent);
task.on("error", logEvent);
task.on("complete", logEvent);
function logEvent(e) {
console.log("----------------");
console.log('Status: ' + e.eventName);
// console.log(e.object);
if (e.totalBytes !== undefined) {
console.log('current bytes transfered: ' + e.currentBytes);
console.log('Total bytes to transfer: ' + e.totalBytes);
}
}
});
}
exports.onTap = onTap;

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.

File upload using AnguarJS

I wanted to upload image in an AJAX manner and did so with reference to this Article
What I have done:
Controller:
$scope.uploadImage = function () {
var result;
var formdata = new FormData();
var fileInput = document.getElementById('fileInput');
for (var i = 0; i < fileInput.files.length; i++) {
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Common/Image_upload?imageType=' + $scope.imageType);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
};
View:
<form id="uploader" ng-submit="uploadImage()">
<input id="fileInput" type="file">
<input type="submit" value="Upload file" />
</form>
MVC Controller:
[HttpPost]
public JsonResult Image_upload(string imageType)
{
....
success = ProductImage_insert(Image);
message = success ? "Image uploaded successfully!" : "Image was not uploaded!";
return Json(message, JsonRequestBehavior.AllowGet);
}
Requirement:
I need to catch this JSON response in the controller, how can I do it?
Thanks in advance.
You can do it in a angular way:
$scope.uploadImage = function () {
var fileInput = document.getElementById('fileInput');
var messageHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' };
messageHeaders['X-File-Name'] = encodeURI(fileInput.files[0].name);
messageHeaders['X-File-Type'] = encodeURI(fileInput.files[0].type);
var fileData = fileInput.files[0];
$http({
url: '/Common/Image_upload',
method: "POST",
data: fileData,
headers: messageHeaders
}).success(function (data, status, headers, config) {
// do what you want with the response
});
}
on the server read Request.InputStream for a file content
[HttpPost]
public virtual ActionResult Image_upload(productType)
{
var xfileName = HttpUtility.UrlDecode(Request.Headers["X-File-Name"]);
var xfileType = HttpUtility.UrlDecode(Request.Headers["X-File-Type"]);
var inputStream = Request.InputStream;
var fileLenght = (int)inputStream.Length;
var bytes = new byte[fileLenght];
Request.InputStream.Read(bytes, 0, fileLenght);
System.IO.File.WriteAllBytes(Server.MapPath("/MyFiles/" + xfileName), bytes);
// return status code 200 or any other data
return new HttpStatusCodeResult(200);
}

Resources