How to download any generated by JS file from firefox addon? - firefox

I need to my extension can generate and save text file inside downloads folder. Just give me example of code how to do it.

The downloads API is what you are probably looking for:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads
The downloads.download() function lets you download a file from a URL to your Downloads folder. Here is the example based on the Downloads.download() page.
function onStartedDownload(id) {
console.log('Started downloading: ' + id);
}
function onFailed(error) {
console.log('Download failed: ' + error);
}
var downloadUrl = "https://www.mozilla.org/media/img/home/2018/cards/irl-season-3.821df676279d.png";
var downloading = browser.downloads.download({
url : downloadUrl,
filename : 'mozilla-home.png',
conflictAction : 'uniquify'
});
downloading.then(onStartedDownload, onFailed);
If you need to download data created in Javascript, then you'll first have to create a URL for that data using URL.createObjectURL()

Related

AJAX Query Not Working After Move to AWS $ CloudFront

After a long time lurking, its time to ask my first question...
I'm having trouble with an AJAX query that used to work prior to moving to AWS.
Previously, My web site was hosted on a WAMP server for testing and development and the following relevant code worked fine.
//Read XML file from disc and send file content to other functions\\
function Get_XML_File(){
var XML_File_Path = File_Path + Client_Code + '/' + ID + '/' + ID + '_Analysed_Wave.web'
var xhttps = new XMLHttpRequest();
xhttps.onreadystatechange = function() {
if (xhttps.readyState == 4 && xhttps.status == 200){
Read_Meta_Data(xhttps)
Read_Time_Status(xhttps)
Read_Wave_Height(xhttps)
;}
};
xhttps.open("GET", XML_File_Path, true);
xhttps.send();
}
//Extract Header Data from XML file\\
function Read_Meta_Data(xml) {
var xmlDoc = xml.responseXML;
// Client//
var Client_ID = xmlDoc.getElementsByTagName('Client_ID')[0].childNodes[0]
var Client_Name = xmlDoc.getElementsByTagName('Client_Name')[0].childNodes[0]
Recently, This site was moved to a Elastic Beanstalk distribution with AWS.
'www.atmocean.com.au' has been provisioned with an SSL certificate using the AWS certificate manager.
'assets.atmocean.com.au' is also covered by an SSL certificate and is mapped to a cloudfront distribution of a S3 bucket.
Within the S3 bucket are xml formatted files with a .web suffix (these are generated by proprietary software.)
When the relevent web page is viewed, the chrome console shows the following error: "Uncaught TypeError: Cannot read property 'getElementsByTagName' of null"
this error is in reference to this line:
var Client_ID = xmlDoc.getElementsByTagName('Client_ID')[0].childNodes[0]
What I can't understand is that when the 'Network' tab of the developer console is viewed, the resource is shown as correctly loaded with a status code of 200.
Further, the file content can be viewed in the 'response' tab.
Does this mean that the file has been correctly downloaded from the server to the client?
If so, why does code that formerly worked without error now fail to get the file content?
Does something other than a standard website configuration need to be provisioned through elastic beanstalk (or other means)?
Thanks in anticipation.
You receive a HTTP 200 meaning the server understand the request and can full-fill the request but then it delivers the content, when you execute Read_Meta_Data it does not mean the full content has been delivered
you could add a console.log(xml) and console.log(xmlDoc) to see the current content of your progress
what I would suggest you leverage your code to add a listener on the completion of the transfer
var xhttps = new XMLHttpRequest();
xhttps.overrideMimeType('text/xml');
xhttps.addEventListener("load", transferComplete, false);
function transferComplete(evt) {
// from here your transfer has been completed
}
note: there's also a loadend method which runs when the load has been completed (wether it has been successful or not - never used it)
Frederic,
Thanks for your response.
The clue was in the following line:
xhttp.overrideMimeType('text/xml');
because the xml files use a custom file extension it was being returned as a text string.
I've changed the function to now read as follows:
//Read XML file from disc and send file content to other functions\\
function Get_XML_File(){
var XML_File_Path = File_Path + Client_Code + '/' + ID + '/' + ID + '_Analysed_Wave.web'
var xhttp = new XMLHttpRequest();
xhttp.overrideMimeType('text/xml');
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200){
Read_Meta_Data(xhttp)
Read_Time_Status(xhttp)
Read_Wave_Height(xhttp)
;}
};
xhttp.open("GET", XML_File_Path, true);
xhttp.send();
}
xhttp.overrideMimeType('text/xml');
And with that one change, all is well with the world. (well my function at least.)

How do I programmatically add a tag to a file uploaded to a community on IBM SmartCloud?

I am uploading the file using the IBM Social Business Toolkit and now want to add tag(s) to it. Either as part of the upload or immediately afterwards. In the javadocs I can see that the FileService has a method to add a comment to a file. I can't see an equivalent for Tags though.
There is a Java method to update a tag on a community file - but it is broken in the most recent version of Smartcloud. It has actually been fixed in the most recent GitHub version of the code but it is not available for download as of April 2015.
The bug is reported here https://github.com/OpenNTF/SocialSDK/issues/1624. The method SHOULD be updateCommunityFileMetadata and with that we could add TAGs as Metadata. That would be simple to add to the end of the "addFile" Java method.
The sample code to TAG a file can be found here in the playgroup - it is updating the Meta Data via JavaScript API
https://greenhouse.lotus.com/sbt/sbtplayground.nsf/JavaScriptSnippets.xsp#snippet=Social_Files_API_UpdateCommunityFileMetadata
to TAG a file use the following
function tagFile(yourFileId, yourDocUnid){
require([ "sbt/connections/FileService", "sbt/dom", "sbt/json" ], function(FileService, dom, json) {
var fileService = new FileService();
var fileId = yourFileId
var docId = yourDocUnid
var tagArray = [];
tagArray.push(docId)
fileService.updateCommunityFileMetadata({
id: fileId,
tags: tagArray
}, communityId).then(function(file) {
dom.setText("json", json.jsonBeanStringify(file));
}, function(error) {
dom.setText("json", json.jsonBeanStringify(error));
});
});
}

Downloading excel file in asp.net mvc

What I'm trying to implement is giving the users the ability to export the grid data to an excel file and download it, with the help of a file save dialog.
Here's how I have coded it right now -
In Javascript -
$.post("/irn/Identifier/Download", { "columnValues": columnValues });
In the Identifier controllers Download action -
public FileResult Download(string columnValues)
{
DTData headlineRows = (DTData)Newtonsoft.Json.JsonConvert.DeserializeObject(columnValues, typeof(DTData));
var e = new Services.DownloadToExcel();
return File(e.WriteData(headlineRows), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "testfile.xlsx");
}
In the DownloadToExcel class, inside the WriteData function I have -
//Here, I'm using the EPPlus library to write the column data to an excel file and then i'm returning the data as a byte array -
//Some code that writes the data
return packages.GetAsByteArray();
When I run this code, I expect to see a File Save Dialog in the browser, but nothing happens. There aren't any errors on the C# or JavaScript side. Can anyone tell me what i could be doing wrong?
bit late but I was having a similar issue. To solve it I used JSON.stringify(columnValues) on the client to convert my data into a json string before sending it to the controller.
Then instead of using
$.post("/irn/Identifier/Download", { "columnValues": columnValues });
try
var columnValuesString = JSON.stringify(columnvalues);
window.location = '/irn/Identifier/Download?columnvalues=" + columnValuesString';
Changing the $.post() to a window.location makes it work.
Then you can deserialize the json string in the controller and your Open/Save dialog should appear after hitting your link.
I hope this helps someone else. Let me know and I can post my code if needed.
Thanks.
If you're testing the site in Internet Explorer, try the following:
Open Internet Options -> Advanced. Click Reset. You can also choose to Restore Advanced Settings.
Open Internet Options -> Security. If zones have been changed at all, click "Reset all zones to default level".
Changes to these settings may affect whether or not Internet Explorer accepts file downloads.
More information here: http://answers.microsoft.com/en-us/ie/forum/ie8-windows_other/ie-8-will-not-let-me-download-any-files-music-pdf/bc59ba24-866b-4dbf-93f2-85ebb9912c2c
You should use IFrame to help downlaoding the file.
function postToIframe( url,data) {
var target = "downloadIFrame";
$('<iframe name="' + target + '" style="display:none"/>').appendTo('body');
$('body').append('<form action="' + url + '" method="post" target="' + target + '" id="postToIframe"></form>');
$.each(data, function (n, v) {
$('#postToIframe').append('<textarea name="' + n + '">' + v + '</textarea>');
});
$('#postToIframe').submit().remove();
}
I solved this but forgot to update here -
This worked -
Inside my class -
private const string MimeType = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet";
private ExcelPackage package = new ExcelPackage();
private FileContentResult excelFile;
Write data using EPPlus
...
...
...
excelFile = File(package.GetAsByteArray(), MimeType, FileName);
return excelFile;

how to programmatically kick off a ssis package in asp.net MVC3 to import excel files

I am having some trouble with a asp.net MVC3 web application that I am developing. I need an upload page which Allows the user to upload excel files and dump them to the file system. I got this to work fine. The next part is the part that I am having trouble with, After I upload the excel files I need to programmatically kick off a SSIS package which I have created already to import the excel files.
Here is what I have so far in code:
//
// POST: /Home/Update/
[HttpPost]
public ActionResult Update(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
ViewBag.Message = "File Uploaded Successfully";
file.SaveAs(path);
}
//Start the SSIS here
try
{
Application app = new Application();
Package package = null;
package = app.LoadPackage( #"C:\Users\Chris\Documents\Visual Studio
2008\Projects\Integration Services Project1\Integration Services Project1
\bin\Package.dtsx", null);
// Execute Package
DTSExecResult results = package.Execute();
if(results == DTSExecResult.Failure)
{
foreach(DtsError local_DtsError in package.Errors)
{
ViewBag.Message("Package Execution results:{0}",
local_DtsError.Description.ToString());
}
}
}
catch(DtsException ex)
{
//ViewBag.Message("{0} Exception caught.", ex);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Update");
}
When I run the code and upload an excel file I get a DtsException caught, which says:
Failed to open package file "C:\Users\Chris\Documents\Visual Studio 2008\Projects\Integration Services Project1\Integration Services Project1\bin\Package.dtsx" due to error 0x80070003 "The system cannot find the path specified.". This happens when loading a package and the file cannot be opened or loaded correctly into the XML document. This can be the result of either providing an incorrect file name was specified when calling LoadPackage or the XML file was specified and has an incorrect format.
I don't understand why it is giving me this because the file path is right I checked and it is exactly correct. I need some help fixing this issue I would greatly appreciate any help you guys can give.
Permissions I should think. Put the file somewhere where account running IIS can see it. Whereever you were planning on deploying it, would be good.

not a valid virtual path - when trying to return a file from a url

We download a file from our CdN and then return a url to that downloaded file to the user. I'm trying to get this implemented so that when a user clicks the download buttton, it goes and test that url to that downloaded file then forces a save prompt based on that local url.
So for example if there is a button called download on the page for a specific .pdf, we ultimately have code in our controller going to the cdn and downloading the file, zipping it then returning a url such as: http://www.ourLocalAssetServer.com/assets/20120331002728.zip
I'm not sure if you you can use the File() method to return the resource to the user as to cause a save prompt when you have a url to the file, not a system directory virtual path.
So how can I get this working with the url? I need the download button to ultimately force a save prompt on their end given a url such as what is generated per this example above? Not I am using POST, not a GET, so not sure which I should use in this case either besides this not working overall to force a save prompt. It is hitting my GetFileDownloadUrl but ultimately errors saying it's not a virtual path.
Here's my code:
#foreach (CarFileContent fileContent in ModelCarFiles)
{
using (Html.BeginForm("GetFileDownloadUrl", "Car", FormMethod.Get, new { carId = Model.CarId, userId = Model.UserId, #fileCdnUrl = fileContent.CdnUrl }))
{
#Html.Hidden("userId", Model.UserId);
#Html.Hidden("carId", Model.CarId);
#Html.Hidden("fileCdnUrl", fileContent.CdnUrl);
<p><input type="submit" name="SubmitCommand" value="download" /> #fileContent.Name</p>
}
}
public ActionResult GetFileDownloadUrl(string fileCdnUrl, int carId, int userId)
{
string downloadUrl = string.Empty;
// take the passed Cdn Url and go and download that file to one of our other servers so the user can download that .zip file
downloadUrl = GetFileZipDownloadUrl(carId, userId, fileCdnUrl;
// now we have that url to the downloaded zip file e.g. http://www.ourLocalAssetServer.com/assets/20120331002728.zip
int i = downloadUrl.LastIndexOf("/");
string fileName = downloadUrl.Substring(i);
return File(downloadUrl, "application/zip", fileName);
}
error: not a valid virtual path
This won't work except the zip file is in your virtual path.
The File method you have used here File(string, string, string) expects a fileName which will be used to create a FilePathResult.
Another option would be to download it (using WebClient.DownloadData or DownloadFile methods) and passing either the byte array or the file path (depending on which you choose).
var webClient = new Webclient();
byte[] fileData = webClient.DownloadData(downloadUrl);
return File(fileData, "application/zip", fileName);
And the lines where you get the index of "/" just to get the filename is unnecessary as you could have used:
string fileName = System.IO.Path.GetFileName(downloadUrl);

Resources