In my application am allowing the user to upload URL of the PDF file. i want to grab only the file name from the URL.
For example: If user uploads the URL as www.gradsch.ohio-state.edu/Depo/ETD_Tutorial/lesson2.pdf than lesson2.pdf should get extracted
code:
function load_file(box) {
var file = document.getElementById('file');
if (file == "") {
alert("Enter File URL");
return false;
}
}
How can i grab only the file name from the URL
As
file.substring
you point on container and try to use substring method on it, not on it's content.
You should use
file.innerHTML.substring instead.
Try using: file.text() or file.val()
Eg.:
return file.text().substring(file.text().lastIndexOf("/") + 1, file.text().lastIndexOf("."));
Or,
return file.val().substring(file.val().lastIndexOf("/") + 1, file.val().lastIndexOf("."));
Related
I'm trying to generate a Excel .xlsx file in a controller action. I would like to have the website show a download prompt to download the resulting file. The controller actions executes fine, but no download prompt is shown. Nothing happens.
I've tried:
MemoryStream mstream = ... //generated file;
return File(mstream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", model.DisplayName + ".xlsx");
I've tried:
return new FileStreamResult(mstream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = model.DisplayName + ".xlsx" };
I've tried:
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + model.DisplayName + ".xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.Write(mstream.ToArray());
Response.End();
return Content("");
I even tried saving the file to disk, then returning via the filepath
return File(filepath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
What am I doing wrong?
Thanks!
I am using the following code in an MVC project.
public ActionResult GetCSV()
{
string filename = "example";
string csv = MyHelper.GetCSVString();
return File(Encoding.UTF8.GetBytes(csv.ToString()), "text/csv", string.Format("{0}.csv", filename));
}
My csv string could look something like this
"Col1,Col2,Col3\nRow1Val1,Row1Val2,Row1Val3\n"
To trigger this download in a new window I call the following JavaScript
window.open('/MyUrl/GetCSV', 'DownloadWindowName');
Add the header as follows.
var cd = new System.Net.Mime.ContentDisposition
{
FileName = model.DisplayName + ".xlsx",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
then return the file as follows
return File(mstream, ".xlsx");
Regarding download prompt. If you mean a prompt where it asks where to save the file, then it depends on how the user has set it up in their browser settings. For example in chrome, users can choose not to get a prompt when downloading files and have it downloaded to a pre specified location like the download folder.
http://malektips.com/google-chrome-prompt-download-file.html#.VM-DbFWsUm8
My extension has saved a CSS file to the user's profile directory. Now, I want to load this CSS file into a window.
sheetsheet/utils seems to have a loadSheet(window, uri, type) method for this (https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/stylesheet_utils) but I can't figure out how to convert my CSS file path into a URI object that is expected.
My code is something like this:
const ssutils = require("sdk/stylesheet/utils"),
windows = require("sdk/windows");
var path_to_file = "c:\users\myname\appdata\local\temp\tmppr9imy.mozrunner\myextension\mycssfile.css"
for (let wind of windows.browserWindows) {
// What is the magic function I need to use?
ssutils.loadSheet(wind, someMagicFunctionHere(path_to_file), "user");
}
The sdk/url module prvcides the function you ask.
const { fromFilename } = require("sdk/url");
...
ssutils.loadSheet(wind, fromFilename(path_to_file), "user");
fromFilename converts a path to a file: URI
I tried using the below code. But it did not work.
public FileResult download(string path)
{
return File(path, "application/pdf", Server.UrlEncode(path));
}
My Ajax Code is:
function fileDownload(path) {
$.ajax({
url: '/Home/download',
data: { path: path },
type: 'POST',
async: false,
success: function (data) { }
});
}
You'll generally want to map the file name to a physical path on the server, e.g. assuming the user selects the file Foo.pdf and all content files are in the ~/Content folder:
public FileResult download(string path)
{
string actualPath = Server.MapPath("~/Content/" + path);
return File(actualPath, "application/pdf", Server.UrlEncode(path));
}
However, from a security viewpoint, allowing a user to directly specify a file name is dubious - you may instead want to consider other alternatives, such as a table or dictionary of available files, and force the browser to select one of the available files via key - this way malicious users can't phish for files which weren't meant to be served.
Edit, after seeing that OP wants to Ajax
Ajaxing the document down should work, although downloading in this way won't render the PDF - you would need to pass the document to a scriptable PDF viewer or similar.
Instead of ajaxing the document, you can instead generate a simple link, button or image which the user can click on to invoke the controller action and download the PDF:
#Html.ActionLink("Click to download", "download", new {path = "MyNicePDF.pdf"})
function DownloadAndReturnBackAttachment(linkHref) {
$.fileDownload(linkHref, {
successCallback: function (url) {
gvScanDocuments.PerformCallback();
gvScanDocuments.UnselectRows();
},
failCallback: function (url) {
alert("A file download error has occurred, please try again.");
gvScanDocuments.PerformCallback();
gvScanDocuments.UnselectRows();
}
});
}
This task is complete using window.location method.
Also You can use HTML tag for this:
download me
public FileResult Download(string path)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = "your file name";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
I use this method the get the urls of ressources contain on web page
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception
{
final String url = request.getURL();
return super.handleResourceRequest(request);
}
But, I made request.getURL(); it returns relative url and not the absolute url.
How can I change it to get the absolute URL?
When I run your code, it does return me absolute URLs, even when my web page contained relative links. That said, it wouldn't surprise me if sometimes, it doesn't. I haven't fully tested this code, but I would think you could try something like this.
Basically, you check to see if the URL is absolute, and if not, you assemble an absolute URL by using the parent BrowserField document URL:
ProtocolController controller = new ProtocolController(_browserField) {
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
String absoluteUrl = null;
URI uri = URI.create(request.getURL());
if (uri.isAbsolute()) {
absoluteUrl = request.getURL();
} else {
String docUrl = _browserField.getDocumentUrl();
String url = request.getURL();
if (url.startsWith("/")) {
// the URL is relative to the server root
URI docUri = URI.create(docUrl);
absoluteUrl = docUri.getScheme() + "://" + docUri.getHost() + url;
} else {
// the URL is relative to the document URL
absoluteUrl = docUrl + url;
}
}
System.out.println(" requesting: " + absoluteUrl);
return super.handleResourceRequest(request);
}
}
Again, for me, I was getting absolute URLs, so I couldn't easily test the code in the branch where the URL is relative. So, it's possible that I'm dropping a "/" somewhere, or not handling file:/// URLs properly.
But, this is a starting point, to workaround your problem.
I have a grid loaded, I want to get the current stores URL which loaded the json data to it , and pass an extra param to it, and load this URL as a pdf, or xls. But how can I get the url?
Get the proxy and ExtraParams:
var url = grid.getStore().getProxy().url;
var params = grid.getStore().getProxy().extraParams;
Then, build the url:
var newUrl = url + '?' + Ext.Object.toQueryString (params);
And the newUrl will be something like this:
your_url_data.json?param1=value1¶m2=value2
I don't think that exists a proxy method that do this but you can extend an existing proxy, as follows:
Ext.define ('MyProxy', {
extend: 'Ext.data.proxy.Ajax' ,
buildInternalUrl: function () {
return this.url + '?' + Ext.Object.toQueryString (this.extraParams);
}
});
And then:
var newUrl = grid.getStore().getProxy().buildInternalUrl ();
Result is the same ;)
Here's you can find the doc of proxies: Ajax Proxy
you can get the stores url by yourGrid.getStore().getProxy().url