How to download and then upload image with AngularJS - javascript

I have an Angularjs 1.5.0 web application which should communicate with a REST-based web service that I had developed (using dropwizard & jersey) and tested that it works perfectly.
The REST web service method is like this:
#POST
#Path("/saveImage")
public Response saveImage(
#FormDataParam("imagefile") InputStream uploadedInputStream,
#FormDataParam("imagefile") FormDataContentDisposition fileDetail) {
// save image on server's file system and return OK
}
Scanned images are available to me by the scanner's local web server through a link like this: http://localhost:9980/thumb/random-generated-guid.jpg
In my angularjs code, I want to send the image which is available with the link above to my REST service.
Does anybody know how to do this?
I tried first saving the image as a blob and then send it to the web service. I could save the image using javascript's XMLHttpRequest but sending always fails.
Code for saving the image as Blob:
var xhr = new XMLHttpRequest();
xhr.open('GET', imageAddress, true);
xhr.responseType = 'blob';
var imageData = null;
xhr.onload = function(e) {
if (this.readyState === 4 && this.status === 200) {
// get binary data as a response
imageData = this.response;
var gatewayResponse = sendToGateway(imageData);
}
};
Code for sending the blob data:
var sendToGateway = function(imageDataBlob) {
var formdata = new FormData();
formdata.append('imagefile', imageDataBlob)
$.ajax({
url: 'http://localhost/eval/saveImage',
method: 'POST',
contentType: 'multipart/form-data; charset=UTF-8',
data: formdata,
dataType: 'json',
})
.done(function(response) {
$log.info("**************** response = " + response);
alert("response:\n" + response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$log.error("!!!! FAIL !!!!!!!!!");
alert("FAIL !!!!!!!");
})
.always(function(){
$rootScope.scannerInactive = false;
doStartPreviewUpdate();
});
};
Actually, the problem is when the sendToGateway(imageData); is called, I get the error:
TypeError: 'append' called on an object that does not implement
interface FormData.
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" :
value );

oops, I found the problem. I should have added the following directives to the $.ajax() call.
processData: false,
contentType: false,

Related

Download and open PDF in IE v11

I am sending byte array from backend and trying to open it with ajax and JS, I am always having corrupted PDf which cannot be opened.
me code is below.
$.ajax({
responseType: 'application\pdf',
sucess: function (response)
{
var blob=new blob([response]),{type:'application\pdf'};
window.navigator.msSaveOrOpen(blob);
}
});
any help would be much appreciated. thank you
Having the same issue with IE, ajax headers fixed the problem
$.ajax({
url: this.href,
cache: false,
xhrFields: {
responseType: 'blob'
},
success: function (data) {
var newBlob = new Blob([data], { type: "application/pdf" })
navigator.msSaveOrOpenBlob(newBlob, "something.pdf");
},
error: function (error) {
console.log(error);
}
});
First, set a break point in the success function, then try to use F12 developer tools to debug your code and make sure you could get the pdf blob. Then, use the window.navigator.msSaveOrOpenBlob() method to download pdf file.
Code as below:
var req = new XMLHttpRequest();
req.open("GET", "/44678.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
var newBlob = new Blob([blob], { type: "application/pdf" })
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
};
More details, you could check this article.
Edit:please check your code, the Ajax method doesn't have the request url and have a spelling mistake at the success function.

Ajax request in es6 vanilla javascript

I am able to make an ajax request using jquery and es5 but I want to transition me code so that its vanilla and uses es6. How would this request change. (Note: I am querying Wikipedia's api).
var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
$.ajax({
type: "GET",
url: link,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success:function(re){
},
error:function(u){
console.log("u")
alert("sorry, there are no results for your search")
}
Probably, you will use fetch API:
fetch(link, { headers: { "Content-Type": "application/json; charset=utf-8" }})
.then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
.then(response => {
// here you do what you want with response
})
.catch(err => {
console.log("u")
alert("sorry, there are no results for your search")
});
If you want to make not async, it is impossible. But you can make it look like not async operation with Async-Await feature.
AJAX requests are useful to send data asynchronously, get response, check it and apply to current web-page via updating its content.
function ajaxRequest()
{
var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
var xmlHttp = new XMLHttpRequest(); // creates 'ajax' object
xmlHttp.onreadystatechange = function() //monitors and waits for response from the server
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //checks if response was with status -> "OK"
{
var re = JSON.parse(xmlHttp.responseText); //gets data and parses it, in this case we know that data type is JSON.
if(re["Status"] === "Success")
{//doSomething}
else
{
//doSomething
}
}
}
xmlHttp.open("GET", link); //set method and address
xmlHttp.send(); //send data
}
Nowadays you don't need to use jQuery or any API. It's as simple as doing this:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.open('GET', 'https://www.example.com');
xmlhttp.send();

jQuery.ajax get image from wcf service and display

I'm trying to download and display an image that is returned from a wcf service using jQuery.ajax. I'm not able to work with the data I've received and I'm not sure why. I've tried a lot of things but nothing seems to work.
Here the service :
public Stream DownloadFile(string fileName, string pseudoFileName)
{
string filePath = Path.Combine(PictureFolderPath, fileName);
if (System.IO.File.Exists(filePath))
{
FileStream resultStream = System.IO.File.OpenRead(filePath);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-www-form-urlencoded";
return resultStream;
}
else
{
throw new WebFaultException(HttpStatusCode.NotFound);
}
}
Here my ajax call :
$.ajax({
type: "GET",
url: apiURL + serviceDownloadFile.replace('{filename}', filename),
headers: headers,
contentType: "application/x-www-form-urlencoded",
processData : false,
success: function(response) {
var html = '<img src="data:image/jpeg;base64,' + base64encode(response) +'">';
$("#activitiesContainer").html(html);
},
error: function (msg) {
console.log("error");
console.log(msg);
}
});
Putting the url in a <img> tag does display the image properly, but since the service requires an authorization header, the page ask me for credentials each time.
So my question is, what to do this the response data so I can display it ? using btoa(); on the response displays an error :
string contains an invalid character
Thanks.
As suggested by Musa, using XMLHttpRequest directly did the trick.
var xhr = new XMLHttpRequest();
xhr.open('GET', apiURL + serviceDownloadFile.replace('{filename}', filename).replace('{pseudofilename}', fileNameExt), true);
xhr.responseType = 'blob';
xhr.setRequestHeader("authorization","xxxxx");
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
}
};
xhr.send();

Download pdf file in response to post request

I want a server-side report to be generated from a javascript object and returned as a PDF. In one request.
I've tried a windows.location.href with the object in the query string, but the query string gets too long.
I've also tried a jQuery post with the object as attachment like this:
$.ajax({
url: "/SalesCalls/SalesCallReport/GetReport",
data: JSON.stringify(unmappedItem),
timeout: 10000,
type: 'POST',
contentType: 'application/json',
success: function (response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) {
var type = request.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
}
}
});
I stole the code in the success callback from another post on stackoverflow. It transfers the object to the server alright, but the output somehow doesn't work, I just get a blank pdf. I can see response contains the binary pdf, so I'm somehow missing a step.
The fact that this runs only on modern browsers is no problem.

error in uploading file data via jQuery Ajax POST request

I am receiving an error trying to upload large than 50kB file via jQuery Ajax POST request.
I am sending the request to OData service ( ASP.Net MVC application)
The error I am receiving in browser console is " 413 Request Entity Too Large "
Below is the code I am using to upload
var fileData =
{
fileBinaryData: encodedData //file data in encoded format ( 64 bit),
Description: "my first file"
};
fileData = JSON.stringify(fileData);
$.ajax({
url: // some odata url ,
type: "POST",
data: fileData,
success: function (res) {
// do something
},
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json");
}
});
a) Is code above the correct way to upload file data via jQuery ajax to a service
b) I have modified my web.config to accept large requests.
c) I do not want to use plugin's like uploadify etc
EDIT 1:
I used javascripts' FileReader() to read the file.
var reader = new FileReader();
//then applied reader.onloadend method etc
if (file.webkitSlice) {
var blob = file.slice(start, stop + 1);
} else if (file.mozSlice) {
var blob = file.mozSlice(start, stop + 1);
}
reader.readAsBinaryString(blob);
Finally settled with using jQuery fileUpload plugin

Categories