Jquery get Request Uri too long - javascript

I have a project which is built on ASP.NET MVC. There is a database table to store user's details including image, an api to output his details and view where i consume the api by ajax call. My api is returning the base64 value of image perfectly, but a 404 error comes saying request uri too long when i try to display the image.
Relevant lines of code are
$.ajax({
url: // url of api,
type: "GET",
success: function (data) {
var preview = document.querySelector('img');
preview.src = data.Image;
}
})

Does your base64-string start with data:image/png;base64,?
Look here for complete example.

Related

Download the returned PDF from Ajax

I have the following action that returns a PDF:
[HttpPost]
public string GetPDF(string data, float scaleFactor)
{
var result = JArray.Parse(data);
using (var fs = new FileStream(#"c:\pdf\pdftest.pdf", FileMode.Create))
{
MemoryStream ms = (MemoryStream)PdfMaker.CreatePDF(scaleFactor, result, dt);
ms.WriteTo(fs);
return Convert.ToBase64String(ms.ToArray());
}
}
(Ignore the FileStream, that is just for testing)
The result is basically the PDF itself, but it's not getting downloaded, how do I download the output PDF? Should I return something else? I tried using a FileResult, but it's basically the same scenario.
This is the way I'm currently "reading" the file via Ajax:
$.ajax({
type: "POST",
url: "home/GetPDF",
data: { data: JSON.stringify(data), scaleFactor: $("#sf").val() },
success: function (data) {
window.location = "data:application/pdf;base64, " + data;
}
});
Thanks.
Edit:
Used the solution in this post provided by Stephen Muecke
Downloading files via ajax doesn't work because the data ends up in memory in a JS object, not on the user's device. Ultimately you need to use a normal HTTP request and return a FileResult.
However in your case you also need to upload some data first which needs to be added to the PDF before it's downloaded. This is awkward because the download will have to be a GET request triggered in a separate window (because you need the application to remain on the same page afterwards) and supplying that data on the querystring is unlikely to be practical.
A solution to work round this is to have a two-step process:
1) From the browser, upload your data via AJAX to a "EditPDF" action method. In the action method, edit the PDF using the new data, and save it. Then return some sort of unique ID to the client which identifies the correct PDF.
2) When the browser receives the response from the EditPDF method, it grabs the returned ID, and makes a new window.open call to the "GetPDF" action's URL. This action accepts the PDF ID as a querystring parameter, so it's easy to include it in the URL when making the request. This action locates the correct document on the server, and returns it in a FileResult. The browser will download the document, while not affecting the HTML page being browsed.

JavaScript Handling different Content-Type in one request

In my project, there is a URL that normally responses an image with Content-Type:image/png that drawn by Java dynamically with user's data.
But sometime causes some reason, the user should not see the image or the image cannot be drawn with user's data. In this case, server will response JSON result that contains error info with
Content-Type:application/json; charset=utf-8
Is this possible to show the image while server response Content-Type:image/png otherwise to alert error info while Server response Content-Type:application/json; charset=utf-8?
I can handle either of the response content type, but struggling with handling both of two content type in one request. is this possible?
EDIT
I tried using AJAX like
<img id="preview-img"/>
$.ajax({
url: "/preview",
type: "GET",
dataType: "JSON",
success: function(data) {
if (!data.success) {
alert(data.msg);
}
},
error: function() {
alert("occur error");
}
});
With above code, alert(data.msg) is available when Server response a JSON result with error message, but alert("occur error") will triggered when Server response correct Image.
And I retried with remove dataType:
$.ajax({
url: "/preview",
type: "GET",
success: function(data) {
if (!data.success) {
alert(data.msg);
}
},
error: function() {
alert("occur error");
}
});
Glad to see the success function is triggered whether Server response Image or JSON
But I don't know how to display Image with response data that looks like
ÿØÿàJFIFÿÛC
$.' ",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀ%a"ÿÄ
ÿĵ}!1AQa"q2¡#B±ÁRÑð$3br
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ
ÿĵw!1AQaq"2B¡±Á #3RðbrÑ
$4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÚ?÷ú(¢
......
A bunch of garbage.
And now I temporarily not to handle JSON result
<img id="preview-img"/>
var image = new Image();
image.onload = function () {
$("#preview-img").attr("src", "/preview");
};
image.onerror = function() {
alert("could not load image");
};
image.src = "/preview";
The request fails with "dataType" set because JQuery tries to parse the response as JSON, but fails to do so if the server responded with an image. Therefore the error-callback is called.
The preferred solution, in my opinion, would be to set an HTTP code != 200 (e.g. 404 for not found) in case the image couldn't be served by the server. The error-callback would be called in that case and you can show an error-dialog the user. Otherwise you can proceed with displaying the image in the success-callback.
Regarding "I don't know how to display Image with response data that looks like" look here: Using jQuery's ajax method to retrieve images as a blob

html2canvas javascript screenshot and upload

Would it be possible to use html2canvas (This) to take a picture of the user`s screen but also upload the image, get the upload link and send it with ajax to the webserver?
if so, how can i do this?
Yes it is certainly possible to do such a thing.
Firstly use the html2canvas api to take a picture of the user's screen:
html2canvas(document.body).then(function(canvas) {
});
Secondly use the following function to convert the returned canvas image into a base64 encoded URL (defaults to png):
canvas.toDataURL();
Specification For canvas.toDataURL
Now construct a request to send your base64 encoded url to an image uploading server (I'm using Imgur as an example).
html2canvas(document.body).then(function(canvas) {
var dataURL = canvas.toDataURL();
$.ajax({
url: 'https://api.imgur.com/3/image',
type: 'post',
headers: {
Authorization: 'yourauthcode'
},
data: {
image: dataURL
},
dataType: 'json',
success: function(response) {
if(response.success) {
// Post the imgur url to your server.
$.post("yourlinkuploadserver", response.data.link);
}
}
});
});
After the image has been uploaded you can POST the URL of the uploaded image to your web server.
Specification for $.post
Specification for $.ajax
This isn't tested, but should work
function screenshot() {
html2canvas(document.body).then(function(canvas) {
// post using your favourite xhr polyfill, e.g. jQuery's
$.post('http://urlgoeshere.com', canvas.toDataURL('image/png'));
});
}
Then decode the result from base64 on the server side and put in a file
Using the example above, don't forget to add this to the base64url, otherwise it won't work :
var dataURL = canvas.toDataURL().replace(/.*,/, '');
More info here.

An AJAX request to get the new upload URL

I'm using Google App Engine for a backend service and I'm trying to upload a file using an AJAX post and their Blobstore API. I got that part working. If you are not familiar with the service, is quite simple. Blobstore API uploads is a two step process: You need to get an upload url and then upload into that url.
Now, I'm implementing an editor, medium.com-like.
The thing is this plugin needs an endpoint for the upload. As my endpoint is not static and I need to update that URL each time, I have prepared an API in the backend that responds with a JSON file with that URL. I'm trying to do an AJAX request to get that URL but I'm getting an error, as the POST request is done to bad url.
This is the POST requet:
INFO 2014-10-19 08:58:22,355 module.py:659] default: "POST /admin/%5Bobject%20Object%5D HTTP/1.1" 200 2594
An this is my Javascript code:
function getURL(callback) {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
dataType: "json",
success: callback
});
};
$('.editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: getURL().done(function(json){return json['url']})
},
embeds: {
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});
I guess I'm doing something wrong with the AJAX return, but if I console.log it I get the result I want. I've read this answer and try to apply it, but I didn't manage to get it working.
Thanks for your time and your help ! :)
If someone ever has the same problem this is the way I solved it. If you are reading this and you now a better one, please, every help is appreciated.
var url; // Set a global variable
// Define the AJAX call
function AJAXURL() {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
success: function(response){
// Sets the global variable
url = response['url'];
}
});
};
// Gets a first upload URL doing an AJAX call while everything keeps loading
AJAXURL();
$('#editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: function getURL() {
// makes a request to grab new url
AJAXURL();
// But returns the old url in the meanwhile
return url;
}
},
embeds: {
urlPlaceholder: 'YouTube or Vimeo Link to video',
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});

How to build a file from binary string using javascript

I am trying to use BusinessObject RESTful API to download a generated (pdf or xls) document.
I am using the following request:
$.ajax({
url: server + "/biprws/raylight/v1/documents/" + documentId,
type: "GET",
contentType: "application/xml",
dataType: "text",
headers: {"X-SAP-LogonToken": token, "Accept": "application/pdf" },
success: function(mypdf) {
// some content to execute
}
});
I receive this data as a response:
%PDF-1.7
%äãÏÒ
5 0 obj
<</Length 6 0 R/Filter/FlateDecode>>
//data
//data
//data
%%EOF
I first assumed that it was a base64 content, so in order to allow the users to download the file, I added these lines in the success function:
var uriContent = "data:application/pdf; base64," + encodeURIComponent(mypdf);
var newWindow=window.open(uriContent, 'generated');
But all I have is an ERR_INVALID_URL, or a failure while opening the generated file when I remove "base64" from the uriContent.
Does anyone have any idea how I could use data response? I went here but it wasn't helful.
Thank you!
. bjorge .
Nothing much can be done from client-side i.e. JavaScript.
The server side coding has to be changed so that a url link is generated (pointing to the pdf file) and sent as part of the response. The user can download the pdf from the url link.
You cannot create file using javascript, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
To achieve your functionality, you can implement click event which target to your required file and it will ask about save that file to user.

Categories