PDF stream works on Chrome, but not IE11 - javascript

I'm streaming a dynamically generated PDF from the server to the frontend. The PDF will display with no issues in Chrome, but generates this error in IE11.
DOCTYPE expected. Consider adding a valid HTML5 doctype: "!DOCTYPE
html"
The PDF is dynamically generated and returns a GUID on success which is then used in the AJAX success to open a link to the new PDF.
On the front end:
$.ajax({
url: "myURL",
method: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: The data used to create the PDF on the server,
success: function (result) {
window.location.href = "newURL?fileIdentifier=" + result;
},
error: function (error) {
console.log(error)
}
On the code behind:
var pdfFilePath = string.Format("{0}\\{1}.pdf", tempWorkPlanDirectory, fileIdentifier);
var fileBytes = File.ReadAllBytes(pdfFilePath);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "inline; filename=\"" + fileName + ".pdf\"");
Response.OutputStream.Write(fileBytes, 0, fileBytes.Length);

Related

Web API controller downloads csv but doesn't work with jQuery

I have a simple web api controller which I can navigate to through the url and it will download the .csv file. Now I am trying to write some jQuery where if you click the button it will download it but I am missing something.
public HttpStatusCode Get(string id)
{
var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id);
var response = HttpContext.Current.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv");
response.Write(reportString);
return HttpStatusCode.OK;
}
This code definitely works and I can go to the URL to prompt the download.
$('.js-btn-download-content').click(function (event) {
var currentLanguage = getCulture();
var url = baseUrl + 'report/get/' + currentLanguage;
event.preventDefault();
$('.loadingContent-download').fadeIn(200);
$.ajax({
headers: {
Accept : "text/csv; charset=utf-8",
"Content-Type": "text/csv; charset=utf-8"
},
url: url,
dataType: "text/csv",
success: function (data) {
$('.loadingContent-download').fadeOut(200);
// Not sure about code below
//var xmlDoc = $.parseXML(data);
//var $xml = $(xmlDoc);
//var $title = $xml.find("200");
//if ($title) {
//$('.contentDownloaded-download p').html('Content donwloaded!');
//$('.contentDownloaded-download').show();
//} else {
//$('.contentDownloaded-download p').html('Download failed! Please try again.');
//$('.contentDownloaded-download').show();
//
}
});
$('.js-btn-confirm').click(function () {
$('.contentDownloaded-download').fadeOut(200);
});
});
As you can see, here is some javaScript that I've been using in the app to handle an OK being returned. However the browser won't download the file when this script fires. Any ideas?
In your Get(string id) method, return the HttpResponseMessage instead of just the HttpStatusCode. Also, ASP.net Web API does not ensure the state of HttpContext.Current.Response (without some wizardry code). You can do something like, change the signature to Get(HttpRequestMessage request, string id) and then call request.CreateResponse(statusCode, data).

Download PDF Using AJAX and TCPDF

I am trying to make a post via AJAX to a PHP script that will then create a PDF.
function getPDF() {
var hashed_center_ids = JSON.parse($('#hashed_center_ids').val());
var print_data = $('.print-options:checked').map(function() {
return this.value;
}).get();
$.ajax({
type: "POST",
url: "<?=site_url('front_office/get_pdf/')?>",
data: {hashed_center_ids : hashed_center_ids, print_data : print_data},
dataType: "text",
success: function(response) {
console.log(response)
var blob=new Blob([response]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="test"+new Date()+".pdf";
link.click();
}
});
}
Once my PDF has been created I return it like so:
return $pdf;
However this just returns,
Message: Object of class TCPDF could not be converted to string
in the chrome console.
Can anybody help me?

Downloading Excel File via webmethod response by ajax calling

I have created a webmethod and the method just send a Excel file as webresponse.When i run only the webmethod it works fine as want
My webmethod is following:
public void Export_ex(string elem)
{
string elements = elem;
HttpContext.Current.Response.ContentType = "data:application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Print.xls");
HttpContext.Current.Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
HttpContext.Current.Response.Write("<head>");
HttpContext.Current.Response.Write("<div>");
HttpContext.Current.Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf- 8\">");
HttpContext.Current.Response.Write("<!--[if gte mso 9]><xml>");
HttpContext.Current.Response.Write("<x:ExcelWorkbook>");
HttpContext.Current.Response.Write("<x:ExcelWorksheets>");
HttpContext.Current.Response.Write("<x:ExcelWorksheet>");
HttpContext.Current.Response.Write("<x:Name>Report Data</x:Name>");
HttpContext.Current.Response.Write("<x:WorksheetOptions>");
HttpContext.Current.Response.Write("<x:ValidPrinterInfo/>");
HttpContext.Current.Response.Write("</x:Print>");
HttpContext.Current.Response.Write("</x:WorksheetOptions>");
HttpContext.Current.Response.Write("</x:ExcelWorksheet>");
HttpContext.Current.Response.Write("</x:ExcelWorksheets>");
HttpContext.Current.Response.Write("</x:ExcelWorkbook>");
HttpContext.Current.Response.Write("</xml>");
HttpContext.Current.Response.Write("<![endif]--> ");
HttpContext.Current.Response.Write("</head>");
HttpContext.Current.Response.Write(elements);
HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
}
but when i call it from javascript function by ajax calling nothing happened. My ajax method is following :
var str = "something"
var data = { elem: str };
$.ajax({
type: 'POST',
url: "ImageSaving.asmx/Export_ex",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
mimeType: 'application/vnd.ms-excel',
success: function (response) {
var show = response.d;
},
failure: function (msg) {
alert("Error occur, could not load the service.");
}
});
I could not understand where i am getting wrong?? Any suggestion regarding this?
For security reasons, you cannot download file from client side. I advice to use a hidden button server side and simulate the click from another button client side.
Regards.

uploading spreadsheet to parse.com from javascript

I am able to upload a spreadsheet (.csv or XLS files), but when checking on the file from Parse.com, it is all empty. I am uploading the file from client side code (not using REST). Do you think that is the problem? This works just fine for a simple image/file upload using a similar code, but fails for csv or xls type file.
Here's the code:
$scope.uploadSpFile = function(fileUpload){
var name = fileUpload.name;
var parseFile = new Parse.File(name, fileUpload.spFile);
var serverUrl = 'https://api.parse.com/1/files/' + fileUpload.name;
var mySpreadsheet = new Parse.Object(fileUpload.className);
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", parse_app_id);
request.setRequestHeader("X-Parse-REST-API-Key", parse_rest_id);
request.setRequestHeader("Content-Type", fileUpload.spFile.type);
},
url: serverUrl,
data: fileUpload.mySpreadsheet,
processData: false,
contentType: false,
success: function(data) {
mySpreadsheet.set({filetitle: data.name});
mySpreadsheet.set({fileurl: data.url});
mySpreadsheet.set({name: name});
mySpreadsheet.set({fileCategory: ''});
mySpreadsheet.set({file: {"name": data.name,"url": data.url,"__type": "File"}});
mySpreadsheet.save();
console.log('file saved!');
},
error: function(data) {
var obj = jQuery.parseJSON(data);
console.log('error: ' + obj.error);
outputMsg = obj.error;
}
});
}
});
when i use a similar code to upload an image, I can access the file on my parse page, but xls or csv files turn out to be empty (actually, in XLS case, an error pops out as the format is corrupted).
Anyone has any idea how to fix this issue?
thanks for the help.

Saving HTML 5 Canvas as Image on the server using ASP.NET

I need some help here..
Im trying to save a canvas image after drawing..
following this example (http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx)
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage?imageData=" + image,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
the controller:
public void UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
But when im trying to convert form base64 the string that is passed like parameter in method, throw an error
Invalid length for a character array Base-64.
You can't post data with querystring parameters
Try this;
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage",
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
In that example, the author has posted the image data using a hidden field, notice below line of code in his article
<input type="hidden" name="imageData" id="imageData" />
http://www.dotnetfunda.com/articles/show/2665/saving-html-5-canvas-as-image-in-aspnet-mvc
And on click of the button, he is submitting the form after getting canvas data to the hidden field so follow the same approach. As written by Mehmet, querystring has limitations and its prone to be modified as it goes via url.
Instead of this
image = image.replace('data:image/png;base64,', '');
use this:
image = image.substr(23, image.length);
remove the leading characters up to the first comma (use any dev tool to see what you posted).

Categories