Weird response received using Promise - javascript

vm.imageR = $resource("", {}, {
getFile: {
url: '/api/imager/:fileId',
method: 'GET',
transformResponse: function(data, headersGetter) { return { data : data }},
isArray: false,
params: {
fileId: '#fileId'
}
},
...
This is what I receive:
"�PNG
IHDRX�7�"�PLTE���V�3R�-���O�(��������������S�/���P�*��h�H��������θ������׫����奥���ᴴ�����ށ��򿿿���O�E������...
How to correctly parse the image to display as image in HTML (set as src in image)?

If you really have to load the image this way, you will have to base64 the image data being returned on the server side and append that string on your img src.
// in this format
var imgData = "data:image/png;base64,"+theBase64Data;
Otherwise you will have to use an image tag to perform the request.
var img = document.createElement("img");
img.src = '/api/imager/'+fieldId; // whatever the fieldId is
// append it to the dom.
The second option make more sense since you are getting the image from the server anyway, why base64 it?

It's weird, but this was the only change that worked:
Before:
vm.getFile = function (fileId) {
return vm.imageR.getFile({ fileId: fileId });
};
Now:
vm.getFile = function (fileId) {
var retVal = vm.imageR.getFile({ fileId: fileId });
return retVal;
};
Really weird. :)

Related

image grabber empty url

urls returns an empty array []
I don't quite understand this part of the code myself as its borrowed,
I either need help understanding the urls part to recode it properly,
or have someone recode it for me which I will try my best to understand.
the urls part was made for google images but Im using another site.
im grabbing images of this site: https://www.desktopnexus.com/search/kitsune+girl/1/
function kitsuneimage(message) {
var options = {
url: "https://www.desktopnexus.com/search/" + "kitsune+girl" + "/" + Math.ceil(Math.random() * (60 + 2)) +"/",
method: "GET",
headers: {
"Accept": "text/html",
"User-Agent": "Chrome"
}
}
console.log(options.url);
request(options, function(error, response, responseBody) {
if (error) {
return;
}
$ = cheerio.load(responseBody);
var links = $(".image a.link");
var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href"));
console.log(urls);
if (!urls.length) {
return;
};
message.channel.send(urls[0]);
});
}
instead of
var links = $(".image a.link")
maybe this should work:
var thumbnails = $("#middlecolumn .thumbnail")
// this is a jquery object, so we need to call get() to turn it into a plain array
var links = thumbnails.map(thumbnail => thumbnail.parent()).get()
var urls = links.map(link => link.getAttribute('href'))
well the thumbnails part does grab the image and it looks like this in the console.log(thumbnails);
'2': {
type: 'tag',
name: 'img',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: [Object: null prototype] {
src: '//cache.desktopnexus.com/thumbseg/1853/1853748-200.jpg',
border: '1',
alt: 'girl',
class: 'thumbnail'
},
but it says in the .parent is undefined
I was thinking maybe replace thumbnail with tag since thats the type it is, would that work?
----EDIT----
well thats wrong because thumbnail is the class of the image in this.
so why is .parent undefined?
This question is closed since I moved on to making a new code with "got" module

How to add custom properties to file form javascript / jquery

I'm aiming to send fileform with images and additional information like height and width. I can't figure out how to add some custom props to file form object.
$("#saveImg").on('click', function () {
var formData = new FormData(),
allFiles = [];
$('input[name=fileUpload]').each(function (index) {
if (inputFileValidation(this)) {
(function (files) {
if (files.length != 0) { allFiles.push(files[0]); }
})(this.files)
}
});
for (var i = 0; i != allFiles.length; i++) {
var img = new Image()
img.src = window.URL.createObjectURL(allFiles[i]);
$(img).on('load', function () {
formData.append("files_h", img.naturalHeight);
formData.append("files_w", img.naturalWidth);
formData.append("files", allFiles[i]);
window.URL.revokeObjectURL(allFiles[i]);
});
}
$.ajax({
url: '#Url.Action("Upload", "Image")',
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function () {}
errors: function () {}
});
});
[HttpPost]
public async Task<IActionResult> Upload (IList<IFormFile> files)
{
//do something ;
}
I also tried:
[HttpPost]
public async Task<IActionResult> Upload (IList<IFormFile> files, IList<IFormFile> files_h, IList<IFormFile> files_w)
{
//do something ;
}
Maybe you have another idea how to send image with additional data? I tried to convert file form and additional info to JSON by that didn't work.
Edit
Thank you all for your suggestion, they are really important to me because I will definitely use them in the future.
However, in this project I have already given up using the file reader due to its asynchrony and having fun with promise. The aim is simple and less javascript and more c#
I apologize for misleading you in the title javascript andjquery - and I mark the answer related to c #. I did this because this answer is related to my next task because the CoreCompat.System.Drawing library is undoubtedly still useful for editing photos in the future.
Thanks!!
If you want to get the Width and Height properties while uploading images in ASP.NET Core. I suggest you to install this package: CoreCompat.System.Drawing
Install-Package CoreCompat.System.Drawing -Version 1.0.0-beta006
In the server, after saving your files to the specific path. You could use System.Drawing.Image class to get the Width and Height properties:
using (var image = System.Drawing.Image.FromFile(filePath))
{
int width = image.Width;
int height = image.Height;
}
You don't have to add files_h and files_w properties to your client model before sending to server.
And then, by using this way, I've edited your js code to:
$("#saveImg").on('click', function () {
var formData = new FormData();
for (var input of Array.from($('input[name=fileUpload]')))
{
if (inputFileValidation(input) && input.files.length) {
formData.append('files', input.files[0]);
}
}
$.ajax({
url: '#Url.Action("Upload", "Image")',
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function () {}
errors: function () {}
});
});
This is one approach; taken from there:
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', ‘Manas’);
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
Another approach is to use the FileReader class to read the uploaded file, convert it to a base 64 string. Then you can send the base 64 string to the server.

How to post an image in base64 encoding via .ajax?

I have some javascript code that uploads an image to a server. Below is the ajax call that works correctly.
$.ajax({
url: 'https://api.projectoxford.ai/vision/v1/analyses?',
type: 'POST',
contentType: 'application/json',
data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }',
})
I now need to upload the image a a base64 encoding e.g.
data: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
But that doesn't work, i.e. the server doesn't recognise the data I send and complains.
Does anyone know what the correct format is for sending base64 encoded data in the AJAX call ?
Thanks for all the answers which helped me along.
I had also posted the question to the forums on
https://social.msdn.microsoft.com/Forums/en-US/807ee18d-45e5-410b-a339-c8dcb3bfa25b/testing-project-oxford-ocr-how-to-use-a-local-file-in-base64-for-example?forum=mlapi (more Project Oxford specific) and between their answers and your's I've got a solution.
You need to send a Blob
You need to set the processData:false and contentType: 'application/octet-stream' options in the .ajax call
So my solution looks like this
First a function to make the blob (This is copied verbatim from someone more gifted than I)
makeblob = function (dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], { type: contentType });
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
and then
$.ajax({
url: 'https://api.projectoxford.ai/vision/v1/ocr?' + $.param(params),
type: 'POST',
processData: false,
contentType: 'application/octet-stream',
data: makeblob('data:image/jpeg;base64,9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
})
.done(function(data) {alert("success");})
.fail(function() {alert("error");});
This is some working code from my own application. You will need to change the contentType and data args in your ajax operations.
var video = that.vars.video;
var code = document.createElement("canvas");
code.getContext('2d').drawImage(video, 0, 0, code.width, code.height);
var img = document.createElement("img");
img.src = code.toDataURL();
$.ajax({
url: '/scan/submit',
type: 'POST',
data: { data: code.toDataURL(), userid: userid },
success: function (data) {
if (data.error) {
alert(data.error);
return;
}
// do something here.
},
error : function (r, s, e) {
alert("Unexpected error:" + e);
console.log(r);
console.log(s);
console.log(e);
}
});
//After received the foto, convert to byte - C# code
Dim imagem = imagemBase64.Split(",")(1)
Dim bytes = Convert.FromBase64String(imagem)
You load the image in canvas, not necessary upload to server.
var ctx = canvas.getContext('2d');
ctx.drawImage(img, selection.x, selection.y, selection.w, selection.h, 0, 0, canvas.width, canvas.height);
var ctxPreview = avatarCanvas.getContext('2d');
ctxPreview.clearRect(0, 0, ctxPreview.width, ctxPreview.height);
ctxPreview.drawImage(img, selection.x, selection.y, selection.w, selection.h, 0, 0, canvas.width, canvas.height);
$('#avatarCanvas').attr('src', canvas.toDataURL());
$('#hdImagembase64').val(canvas.toDataURL());
See, this code get image and draw in canvas, after draw you get base64 string with canvas.toDataURL()
try this :D
The data parameter for jQuery's $.ajax call can be a String, Object, or Array. Based on the working example you gave, it looks like your upload script expects a parameter called "Url":
data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }'
If you wanted to pass the parameter as an Object, you might try:
data: {
Url: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
}
If you want to pass it as a String, you might try:
data: '{ "Url": "data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z"}'

How save image in parse cloud using javascript

we are trying to save image in Parse using CloudCode.
we followed this link.
we are new to javascript,plz guide us...!
Thanks in advance.......
var url = file.url();
Parse.Cloud.httpRequest({ url: url }).then(function(response) {
// Create an Image from the data.
var image = new Image();
return image.setData(response.buffer);
}.then(function(image) {
// Scale the image to a certain size.
return image.scale({ width: 64, height: 64 });
}.then(function(image) {
// Get the bytes of the new image.
return image.data();
}.then(function(buffer) {
// Save the bytes to a new file.
var file = new Parse.File("image.jpg", { base64: data.toString("base64"); });
return file.save();
});
we getting error like this
There's a repeated syntax mistake at the end of each function parameter to then.
The syntax is:
somePromise.then(function() {
// success
}).then(function() { // your code says '}.' instead of '}).'
// success
});
There's an optional error function callback as second param:
somePromise.then(function() {
// success
}).then(function() {
// success
}, function(error) {
// error
});
You are missing the close parentheses for each promise callback. Your code should be this :
var url = file.url();
Parse.Cloud.httpRequest({ url: url }).then(function(response) {
// Create an Image from the data.
var image = new Image();
return image.setData(response.buffer);
}).then(function(image) {
// Scale the image to a certain size.
return image.scale({ width: 64, height: 64 });
}).then(function(image) {
// Get the bytes of the new image.
return image.data();
}).then(function(buffer) {
// Save the bytes to a new file.
var file = new Parse.File("image.jpg", { base64: data.toString("base64"); });
return file.save();
});

How to connect jsReport in AngularJS?

I have a problem now about JSReport.. It assumed that I already have an API...What I want now is how to link it with my Client Side which uses AngularJS.
If I use Postman it will return a pdf file which is what I want. But my problem is how to show it is my page when i post it using angularjs..
I have a code like this :
Controller
$scope.Print = function () {
authService.print().then(function(result){
var _result = result;
});
};
Service
var _print = function () {
var data = { "template": { "shortid": "byQtwHLPQ" } };
return $http.post("http://192.168.8.87/api/report", data).then(function (result) {
return result;
});
};
authServiceFactory.print = _print;
Now I have that Code and its not working... I assumed it has no return so I remove the return and just post but still it didn't work and even downloading the pdf didn't work on it.
Anyone can help Please...
Use like this one..
Controller
var parameter = { "template": { "shortid": "ZkMoslfdX" }};
PrintService.Print(parameter).then(function (result) {
var file = new Blob([result.data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
Service
var reportUrl = "http://192.168.8.87/api/report";
var _print = function (parameter) {
return $http.post(reportUrl, parameter, { responseType: 'arraybuffer' }).success(function (response) {
return response;
});
};
The main idea is that the result.data is converted into a blob and create an objectURL so that it is readable and to the object tag and $sce.trustAsResourceUrl used to trust angular to your URL
HTML
<object data="{{content}}" type="application/pdf" style="width:100%;height:80%"></object>
I refer to this post AngularJS: Display blob (.pdf) in an angular app for clarification just read that one.

Categories

Resources