Open a file in new tab using ajax - javascript

I'm using Iron PDF to Generate pdf documents from an HTML string. After the file generated i want to open the file in a new tab using ajax call
Here is my ajax post
$.post($('#WebSiteUrl').val() + "Print/PrintAsync",
{
id: id,
},
function (response) {
window.open(response, '_blank');
}
});
This won't work.
In the above code, I can return the response as a byte array or FileContentResult.
how can it possible to open as a file in another tab

Simply use get instead of post and return FileContentResult in your asp.net MVC project and open a new tab by javascript like this.
window.open($('#WebSiteUrl').val() + "Print/PrintAsync", "_blank");
Don't forget to set content type to application/pdf when you return FileContentResult.

Related

How can we download the dynamically generate file from server?

I want download the file from server (I knew that we can't use AJAX, and serve is Servlet) and which dynamically generate according to the parameters.
Now I have the parameters in format JSON, like:
{"limitTo":"name","searchFor":["AAA","BBB","CCC"],...}
So, how can we send the request to the server with those paraleters? Do we need create some inputs?
Thanks, I found the solution which uses dojo/request/iframe, without window.open
And the code likes :
require(["dojo/request/iframe"], function(iframe){
// cancel the last request
iframe._currentDfd = null;
iframe("something.xml", {
handleAs: "xml",
data : "your json"
}).then(function(xmldoc){
// Do something with the XML document
}, function(err){
// Handle the error condition
});
// Progress events are not supported using the iframe provider
});
And then we can see download window.
Here is an article about dojo/request/iframe

call javascript from servlet in java?

I want to call a function of javascript from servlet.
servlet code:
File ff = new File(uploadedFile+"/"+fileName+".mp4");
FileOutputStream fileOutSt = new FileOutputStream( ff );
fileOutSt.write(data);
fileOutSt.close();
request.setAttribute("src", ff);
RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/jsfunction.js");
dispatcher.include(request, response);
my javascript code:
myfunction(fileInput)
{
var fileUrl = window.URL.createObjectURL(fileInput);
}
The problem is javascript calls but it display the code content but not execute it.
how can i get fileURL.
Several things are wrong here:
First, the inclusion of your javascript source is improper, because the javascript must be included (or referenced) always within an HTML file. In your case, instead, you are serving a MP4 file.
If you must absolutely execute that js code (remember that js is always executed in a browser), I suggest you serve an HTML page instead. In this case, the jsfunction.js script must be referenced within the HTML code:
<html>
<head>
<script type="text/javascript" src="jsfunction.js" />
</head>
<body>
...
</body>
</html>
Second: Even if you include the script, you must then invoke your function. You can call it immediately, from a scriptlet, or as a response to some client event (onclick, onload, etc).
javascript plays on client side and Servlet plays on server side. You cannot execute Javascript on serverside. It should execute by browser.
I suggest you to make a javascript call in window onload.
RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. But not to JS. Since JS always runs in browser itself.
request.setAttribute("filename",filenamehere); //put filename
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/filename.jsp");//dispatch here
requestDispatcher.forward(request, response);
In filename.jsp
String value = (String)request.getAttribute("filename");//getting filename
Do like this. This way we will get the file url.
How to pass response from servlet to html
Call your servlet in same html using ajax with jquery.
In servlet
//getting input from `html` page
String userName = request.getParameter("userName").trim();
//now process your request here
//forward response to `html` page
response.setContentType("text/plain");
response.getWriter().write("your file url");
In html call this servlet using ajax
$.ajax({
url : 'yourservletaction',
data : {
userName : $('#userName').val()//if you want to send any input do like this
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);//getting file url as response. so use this url in you js
}
});

Opening a JSON file from javascript

I have a C# functoin in my MVC application that returns a JSON representation of a csv file. I am trying to catch that in javascript and open the file. Basically I want the browser do its thing and let the user decide if he want to open it, save it or cancel. I am unable to get that popup to ask me to open the file. Below are the functions
C# Function
[HttpPost]
public ActionResult ExportToCsv(string fileContents, string fileName)
{
fileContents = fileContents.Replace("-CARRIAGE-", "\r\n");
return Json(new { url = File(Encoding.UTF8.GetBytes(fileContents), "text/csv", fileName) }); ;
}
This is the javascript where I am making the ajax call to the function
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
$.ajax({
url: "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.csv",
type: 'Post',
success: function (result) {
window.open(result.url);
}
});
});
I know I am missing something. Can someone please help.
EDIT
After reading through all the potential answers and comments, this is what I am trying to achieve. So if my code is all horribly wrong please let me know.
I have a grid and I have an export to excel button. I have a method that converts the data i want into comma delimited text in javascript itself. I need to present this to the user as a downloadable csv file. For this I was creating the File object using the controller method. The previous incarnation was a Get method and I faced limitations due to querystring length restrictions. So I tried converting it to a POST method and it is not working.
This is the previous version of the code that works for smaller amounts of data
Javascript
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
window.location.href = "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.csv";
});
C# Function
[HttpGet]
public ActionResult ExportToCsv(string fileContents, string fileName)
{
fileContents = fileContents.Replace("-CARRIAGE-", "\r\n");
return File(Encoding.UTF8.GetBytes(fileContents), "text/csv", fileName);
}
Hope this now gives you all more context. Basically I needed to convert my GET method to a POST method and use it from Javascript.
If you use ajax, you're expected to handle the result in code. But you can't trigger a file download (directly) that way.
Instead, create a (hidden) form and post it to a (hidden) iframe (by giving the iframe a name and specifying that as the target of the form), making sure that the response specifies the header Content-Disposition: attachment. That will trigger the browser to offer to save the file. Optionally in the header you can suggest a filename for the file by adding ; filename="fname.ext" to the header value. E.g. Content-Disposition: attachment; filename="fname.ext".
The client-side looks something like this:
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
var frame = $('iframe[name="formreceiver"]');
if (!frame.length) {
frame = $('<iframe name="formreceiver"></iframe>').appendTo(document.body).css("display", "none");
}
var form = $("#senderform");
if (!form.length) {
form = $('<form id="senderform"></form>').appendTo(document.body);
}
form = form[0]; // Raw DOM element rather than jQuery wrapper
form.target = "formreceiver";
form.action = "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.csv";
form.method = "POST";
form.submit();
});
The server side is just a standard form response with the Content-Disposition header.
I've used this technique for years, with browsers from IE6 onward. My usual setup already has the iframe in the markup (rather than creating it as above), but other than that this is basically what I do.
Note that it's important you're doing this in response to a button click by the user. If you weren't, there would be popup-blocker issues.
You can't save binary files using ajax - it's restricted due to security reasons. If you'd like the user to save the file - return a binary stream from your controller as you post the data back in JSON format (ie if the user wants to save it).
I've done a similar thing here: How to properly create and download a dynamically generated binary *.xlsx file on .net MVC4?
Maybe save it as a json file instead and load in the current page's DOM. Although I though I am confused, don't you just have a JSON response containing a URL to your CSV file is which is just that a CSV file, not a JSON representation of CSV?
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
$.ajax({
url: "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.json",
type: 'Post',
success: function (result) {
var myDummyElement = $('<div>'); //dummy div so you can call load
myDummyElement .load('result.url #myJson');
}
});
});
<div id="myJson"></div>
[HttpPost]
public ActionResult ExportToCsv(string fileContents, string fileName)
{
//change fileName to be a .json extension
fileContents = fileContents.Replace("-CARRIAGE-", "\r\n");
return Json(new { url = File(Encoding.UTF8.GetBytes(fileContents), "text/csv", fileName) }); ;
}

how to export csv file with filename

I want to export the exist data into csv file. I try to use this code:
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();
it works but I can design filename. I can only get the dialog with name like "MVeAnkW8.csv.part" which I don't know where the name come from.
How can I assign filename in the first dialog? Thanks in advance.
update:
I am now using rails. Actually I have a method in server side names export_to_csv. In end of this method, I use code like that:
send_data(csv_string,
:type => 'text/csv; charset=utf-8;',
:filename => "myfile.csv")
It works and I can specify the file name.
For now, I want to use ajax to get more csv files(that is the reason why I want to use javascript, because a normal http request can only get one file to be downloaded).
I use js code like that:
$.post("export_to_csv",
function(data) {
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();});
It get the data from server side and I try to transfer it into csv. I can get a file but can't specify the file name.
As I know, you can specify the filename only in chrome 14+.
Take a look at this question: Is there any way to specify a suggested filename when using data: URI?
Update!
If you want to download multiple csv files "at once", you can zip them together, or save each file on the server separately (each file now has a url that points to it - if you place them inside the 'www' folder).
Then send the file names and their path/url to the client via ajax (use a json encoded list for example).
In the ajax callback function: take the list of the files and open each file-url in a separate popup.

Generating file with ajax and allow user to download it?

I have very similar problem as this: Allowing users to download files - ASP.NET , but in my case I am generating xlsx file with ajax, and on ajax-called aspx page I am using:
Response.Clear();
Response.ContentType = "application/octet-stream";
string filename = User.Identity.Name + "_Report.xlsx";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.WriteFile(AppDomain.CurrentDomain.BaseDirectory + "Reports\\" + filename);
Response.End();
When this file is generated, control is returned to ajax calling page and from there I wan't to show save file dialog based on this ajax response and allow user to download this generated file. I don't want to save file on disk with ajax called page and then redirect ajax calling page to that file, because of popup blocker in IE. I am using jquery for ajax calls:
$.ajax({
type:"POST",
url: "AjaxReport.aspx",
data:dataString,
success: function(data) {
//don't want to use this
// $('#RedirectIFrame').attr('src','Reports/Report.xlsx?cache='+Math.random());
//want to use data variable containing ajax response (bytes of Report file) showing
//save dialog to download this file from browser
}
});
How to do this?
Currently JavaScript can't access to the user's file system, meaning you can't prompt users to save a file coming from a network stream.
In other words. You'll need to do that redirect and write your file stream to the HTTP response and let the user decide what to do :)

Categories

Resources