I have problem with downloading files in Firefox. I tried to find solution in old posts but I didn't find anything. I understand that solution is very simple, but I think today is not my lucky day :)
Simple example. I try to call a web method from JavaScript and download a file.
Client code:
<script language="javascript" type="text/javascript">
function Test() {
PageMethods.Test(onCompleted);
}
function onCompleted(result) {
window.open(result);
}
</script>
........
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
<input type=button value="Download" onclick="Test()"/>
</div>
Server side:
[System.Web.Services.WebMethod]
public static string Test()
{
return "\\Files\\test.zip";
}
Folder 'Files' lies in root folder of Web application.
For IE and Chrome, this code is working fine, and I can download the file. But in Firefox, I get an error:
Server Error in '/' Application.
HTTP Error 400 - Bad Request.
and in url I can see for example:
http://localhost:1406/\Files\test.zip
How can I return the correct path to zip file?
URL don´t allow for backslashes.
If the file is located at \Files\test.zip on your windows webserver root the correct url to the file is http:///Files/test.zip
Change the server side code to:
[System.Web.Services.WebMethod]
public static string Test()
{
return "/Files/test.zip";
}
Web URLs should use forward-slashes instead of backslashes.
In general you should use ResolveUrl method of the System.Web.UI.Control class. But in case of static method there is some workaround solutions.
Replacing the following lines
[System.Web.Services.WebMethod]
public static string Test()
{
return "\\Files\\test.zip";
}
with these might work...
[System.Web.Services.WebMethod]
public static string Test()
{
return "\\\\Files\\test.zip";
}
Related
I have the following script tag in my JSP file:
<script src="/js/CCTUtil.js"></script>
with the following function in it:
function disableButton(buttonID) {
document.getElementById(buttonID).setAttribute("disabled", "true");
return true;
}
and in my jsp I call it with:
onchange="disableButton('datasourceForm:cancel');
datasourceForm:cancel is just the ID, so don't worry about that.
This works if I hardcode the JS function in my JSP, but when exporting it to a file, it doesn't work. It recognizes the valid filepath (otherwise the server throws an exception) so it can see the file just fine, but when testing it in Internet Explorer the error is "Object expected", and points to the end of the JSP file, which of course isn't telling of anything.
Help please?
The SRC must not be correct then. Are you sure you have set the path correctly? It's not supposed to be "../js/CCTUtil.js" is it?
Instead of including script file, directly add javascript function in the jsp file.
Then try, if you are getting the same issue, might be some issue with javascript or ur id datasourceForm:cancel
I want to create a calculator which is able to evaluate Strings like 3+(2-1)*2 or (28.4/2-1.5)+(4-2). I searched the web and found the possibility to use a WebView with JavaScript enabled which can evaluate() Strings.
How do i use JavaScript in a WebView?
How can i pass for example input.getText().toString() to the JavaScript and get back a value?
How do i access evaluate() of JavaScript in my Java-code?
I found a tutorial here. I have to load the HTML-file into my WebView, don't i?
You are going right. For using javascript in webview, after you load url to webview,(you can catch to page loading done at onPageFinish function) at onPageFinish function, you call js like this:
But first you must give permission to webview with these code blocks:
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
webview.loadUrl("javascript:setPageHeight("+contentHeight+");"); // you can pass param with call js function at loaded page.
webview.loadUrl("javascript:alert('test');"); // or you can call like this
For take result param from webview with js you must a subclass like this:
class JavaScriptInterface {
public void showToast(String msg) {
Toast.makeText(mContext, "Received Msg :" + msg,Toast.LENGTH_SHORT).show();
}
}
Then you give this to your webview at the define webview lines
webview.addJavascriptInterface(new JavaScriptInterface(), "MyAndroid");
Finally you call java function in your html in js like this:
<html>
<head>
<script type="text/javascript">
function sayHello(msg){
//calls Android's JavaScriptInterface Function
MyAndroid.showToast(msg);
}
</script>
</head>
<body >
<div onclick="sayHello('hello')"> Click Me !! </div>
</body>
</html>
In my project, I have a file that I want the user to download. When they click on the link, I want a popup window to display "Your download will shortly, if it doesn't start click here". After a few seconds, it will then close and the actual file download will then display.
I know to achieve the window closing you'll use:
window.setTimeout(function(){window.close()}, 5000);
But I'm not sure how you would call the download once the window has closed?
Cheers for any help!
In simple way, use window.open() to start download file.
Direct link
<script type="text/javascript">
setTimeout(function() {
window.open("myfile.doc");
},3000);
</script>
Okay so I don't know your platform so will give an ASP.NET version. If you are using something else then I have commented so you should be able to adapt to your platform.
EDIT: Now know user is using PHP so added code snippet for PHP (not robust but I'm no PHP dev)...
1) SAME FOR PHP/ASP Are you getting a file that will not be displayed by the browser automatically? i.e. .js will be shown as is but an exe will probably trigger a file download dialog (someone correct me if wrong please and I'll update)
If your files are always going to be i.e. .exe then you could probably just get away with:
$("body").append("<iframe src='http://www.targetsite.com/files/thefilename.exe'></iframe>");
but more likely you will be using a parameter to find the right file (and hide direct download
$("body").append("<iframe src='http://www.targetsite.com/downloader/?file=1234-1234-1234'></iframe>");
in some setTimeout function.
If the filetypes are unknown then I suggest pointing the above code at a script file (.ashx, php, etc) that writes the file byte stream to the http response.
FOR PHP:
<?php // Demo - send a (binary) file
$file = "ireland.jpg";//here you would use the query string parameter of the above
//ajax/iframe request eg file=1234-1234-1234 to find image in db
$fp = fopen($file,"r") ;
header("Content-Type: image/jpeg");//this would need to be modified to either show right content type or you could
//set it to Application/force-download
while (! feof($fp)) {
$buff = fread($fp,4096);
print $buff;
}
?>
WARNING Be careful with the above code. It occurred to me you might pass in filename directly which I'm pretty sure someone could use to get files in other places in your app without careful attention
FOR ASP:
I have included an example ashx (generic handler) solution:
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wardle.PdfGenerator;
using System.IO;
public partial class user_account_iframedownloader : System.Web.UI.Page
{
private IInformixRepository _rep;
//this page gets loaded into an iframe so we can do downloads while using ajax
protected void Page_Load(object sender, EventArgs e)
{
//write bytes out here i.e. see after for methods
}
}
Example byte output methods (you just need to do File.getBytes or something - my code is quite complicated so 'excercise for reader'
public static void PdfOutput(byte[] pdfData, string filename)
{
HttpContext.Current.Response.ContentType = "Application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename);
HttpContext.Current.Response.BinaryWrite(pdfData);
}
public static void PdfZipOutput(byte[] zipData, string filename)
{
HttpContext.Current.Response.ContentType = "Application/zip";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename);
HttpContext.Current.Response.BinaryWrite(zipData);
}
In a c# aspx project.
I can reach a static method on client side with importing my namespace at the beginning part of the page, as follows.
<%# Import Namespace="utl=portal.library.Utilities" %>
And than in can use that on client side of the same asxp page like.
<script type="text/javascript">
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
</script>
My question is, can i use that '<%= utl.getcategoryName().ToString() %>' in an external javascript file ?
Is it possible something like that ?
<%# Import Namespace="utl=portal.library.Utilities" %>
<script src="/scripts/trial.js" type="text/javascript"></script>
and in the trial.js file
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
thanks in advance..
I don't think so, because the external .JS file wouldn't be processed by ASP.NET and therefore wouldn't have access to those kinds of variables.
I don't think you can but you could instead try to pass the server side variable as a parameter to a JS function in the external JS file.
You can create a .aspx file that only outputs Javascript instead of HTML. As long as you set the Content Type to application/x-javascript in the code behind, it will work.
For example, create Test.js.aspx. Then, in the code behind for Test.js.aspx.cs:
protected void Page_Load( object sender, EventArgs e )
{
Response.ContentType = "application/x-javascript";
}
protected string GetMessage()
{
return "Hello, World!";
}
In the Test.js.aspx file:
window.onload = function() {
var msg = <%=GetMessage() %>
alert(msg);
}
Now, it is true that the Javascript running on the client can't call C# functions running on the server. You would need AJAX for that. But you can certainly use this pattern to generate Javascript that make use of ASP.NET when it is generated.
Is there any tool to make adding files to MVC3 razor pages faster?
I find myself having to drag script files onto the page to generate:
<script src="../../Scripts/rails.js" type="text/javascript"></script>
Which then i'll copy and paste
<script src="#Url.Content("~/Scripts/")" type="text/javascript"></script>
Then cut/drag the rails.js fragment into the new script statement. Then at some point after this hopefully I remember I need to clean up a whole bunch of duplicated and/or broken script links.
There has to be a better way than this that doesn't involve typing urls out manually.
Came across this blog post earlier today and ASP.NET MVC Best Practices (Part 1) and it's guidance shows
public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/images/{0}".FormatWith(fileName));
}
public static string Stylesheet(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/stylesheets/{0}".FormatWith(fileName));
}
public static string NoIcon(this UrlHelper helper)
{
return Image(helper, "noIcon.png");
}
This seems like the optimal solution if you use a good layout scheme for your resources.
Edit: FWIW
public static string FormatWith(this string format, params object[] inputs)
{
return string.Format(format, inputs)
}
You can use T4MVC to get a compile-time validation your your links.
2.3. Strongly typed links to script files and static resources
T4MVC generates static helpers for
your content files and script files.
So instead of writing:
<img src="/Content/nerd.jpg" />
You
can write:
<img src="<%= Links.Content.nerd_jpg %>" />
Likewise, instead of
<script src="/Scripts/Map.js" type="text/javascript"></script>
You
can write
<script src="<%= Links.Scripts.Map_js %>" type="text/javascript"></script>
The obvious benefit is that you’ll get
a compile error if you ever move or
rename your static resource, so you’ll
catch it earlier.
Another benefit is that you get a more
versatile reference. When you write
src="/Content/nerd.jpg", your app will
only work when it’s deployed at the
root of the site. But when you use the
helper, it executes some server side
logic that makes sure your reference
is correct wherever your site is
rooted. It does this by calling
VirtualPathUtility.ToAbsolute("~/Content/nerd.jpg").