I have used cordova(navigator.camera.getPicture) to capture image from device. I converted the fileURI into base64 using file reader. But, when i assign the base64 url as img src whereas If i pass the same string to HTTP adapter(Worklight), I saw the encoded data truncated. Please help.
Thanks in advance.
Source Code:
function tryToSend(evt) {
encoding = evt.target.result;
console.log("Encoded File: "+encoding);
Ext.ComponentQuery.query('#encodedImage')[0].setHtml('<img style="height: 100px; width: 100px;" src="'+encoding+'" />');
Ext.ComponentQuery.query('#encodedImage')[0].setHidden(false);
}
function win(file) {
alert("FileName:"+file.name + ' & Type:' + file.type);
selectedFileName = file.name;
Ext.ComponentQuery.query('#originalImage')[0].setHtml('<img style="height: 100px; width: 100px;" src="'+file.fullPath+'" />');
Ext.ComponentQuery.query('#originalImage')[0].setHidden(false);
var reader = new FileReader();
reader.onloadend = tryToSend;
var encoded = reader.readAsDataURL(file);
}
function fail(error) {
console.log(error);
}
function onResolveSuccessCompleted(fileEntry) {
fileEntry.file(win, fail);
}
function onResolveFailed(error) {
console.log(error);
}
//Call on click of take pic button
function capPic(){
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
mediaType: navigator.camera.MediaType.ALLMEDIA,
});
}
//Success
function onCapturePhoto(fileURI) {
window.resolveLocalFileSystemURI(fileURI, onResolveSuccessCompleted, onResolveFailed);
fileDetails.push({
base64ImageData:encoding,
fileName: selectedFileName,
});
alert("File Selected. Please Upload Now");
}
//Sending fileDetails array to HTTP adapter as parameter
var invocationData = {
adapter : 'SAMPLE_ADAPTER',
procedure : 'uploadFileNow',
parameters : [fileDetails]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : fileUploadOK,
onFailure : fileUploadFail,
});
1) In Logcat, encoding in tryToSend Fn prints completely whereas the next line console.log gives truncated code
//Ajax call
Ext.Ajax.request({
url: url,
method:'POST',
params:fileDetails,
success: function(response){
console.log(response);
},
failure:function(response){
console.log(response);
}
});
In my logcat the console.log can only print about 4k characters one time. So try to compare the encoded url's length to check if it's really be truncated.
Related
I am performing an Ajax (JQuery) request on a php script which iterates. At each iteration I do an "echo" of the value of the loop counter, encoded in JSon. The goal is to manage the display of a progress bar.
By doing this I hoped to intercept and retrieve each of the counter values in a separate response thanks to the "progress" event.
Actually I only have one answer which contains all the counter values.
My research always leads me to information about downloading files, which is not my situation.
Maybe I should use the "onreadystatechange" event, but I don't see how to fit it into my code: $ Ajax parameter or separate function?
If anyone has an idea to solve my problem.
Here is my JS code
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
$("#xhr-rep").css("display", "block");
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var compteur = evt.text;
$("#xhr-rep").html(compteur);
}
}, false);
return xhr;
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}
I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);
I'm new to NativeScript and I'm trying to capture an image with the camera module (this works fine), and convert it to base64 (this is not working) and POST to server.
I've googled for days. Any help you can lend would be immensely appreciated.
I've tried this about 16 billion different ways and this is my current code:
viewModel.takePicture1 = function() {
camera.requestPermissions();
var isAvailable = camera.isAvailable();
console.log(isAvailable);
var options = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture().then(function (img) {
try{
var imageData = img.toBase64String("jpeg"); // fails here
console.log(imageData);
}catch(err){
console.log("Error: "+err);
}
http.request({
url: "http://[server address]/lab/ns_exp/upload_test.php",
method: "POST",
headers: { "Content-Type": "application/base64" },
content: imageData
}).then(function() {
console.log("Upload successful");
}).catch(function(e) {
console.log("Unsuccessful upload", e);
});
});
}//
Oh, I do want to make clear that I'm not using angular (obviously), so please don't provide an answer that does so. : ) (Vuejs Holdout)
The key here is that base64 needs to know that the image is a JPEG, and what quality the image should be. The code should look like this:
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
Just in case someone finds this later and wonders about putting the image (UI) and/or the image (base64) into an observableArray, here is my complete function:
viewModel.takePhoto = function(){
var self = this;
camera.requestPermissions();
var cameraOptions = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
self.photoData.push({"data": base64});
var image = new imageModule.Image();
image.src = imageAsset;
self.photoUI.push({"src": image.src});
listView.refresh();
})
}).catch(function (err) {
console.log("Error -> " + err.message);
});
}
I have a problem with my dropzone,
$(".js-example-basic-multiple").select2();
Dropzone.options.dropZone = {
//options here
maxFilesize: 2,
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: host+'upload/unfile',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
//console.log();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
}
}
My problem is, when a file fails to upload, it still shows the preview images, so i need that file to be removed automatically when these file fails to upload, how can I do that??
I think, if I understand you correctly, you can just delete the image with this code:
Dropzone.options.dropZone = {
...
, error: function(file, message, xhr) {
$(file.previewElement).remove();
},
...
}
Just read the documentation again.
This code is from the docs:
myDropzone.on("error", function(file) {
myDropzone.removeFile(file);
});
Please let me know, if it works in your case.
When connect error is "xhr.ontimeout", function "error:" don't run.
I need (paste next to "init:"):
sending: function(file, xhr, formData) {
//Execute on case of timeout only
xhr.ontimeout = function(e) {
alert('connection interrupted');
};
}
$.ajax({
type: 'GET',
dataType: 'image/jpeg',
url: '/Home/GetImage/' + img ,
success: function (data) {
i = new Image();
i.src = data;
$('#imageresult').append(i);
},
error: function () {
alert('error');
},
});
[HttpGet]
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);
return File(stream.ToArray(), "image/jpeg");
}
It always falls into error function. If i remove dataType, then it doesn't fall into error function but it just shows long strings in the view. Why doesn't that work and show image in view?
You can do something Like this:
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);
return Json(Convert.ToBase64String(stream.ToArray()), JsonRequestBehavior.AllowGet);
}
and the Ajax call:
$.ajax({
type: 'GET',
url: '#Url.Action("GetImage", "Home")',
success: function (data) {
$("#ItemPreview").attr('src', 'data:image/png;base64,' + data);
},
error: function () {
alert('error');
},
});
and the view:
<img id="ItemPreview" src="" />
of course you can append img dynamically, then bind its source after.
You are confusing the URL of an image with its actual content (the graphic bytes).
The /GetImage call returns the bytes, but you can never put data bytes in the i.src attribute because that attribute needs to be fed a URL.
It might work if you forget about the Ajax call and just use i.src = '/Home/GetImage/' + img;.