How to load CSS file from profile directory (how to create URI from filepath) - firefox-addon

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

Related

Uri is not supported when saving pdf in server folder with nreco pdf generator

I have the following code:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "~/files/";
htmlToPdf.GeneratePdf(template);
Which throws the following error:
Uri is not supported when saving pdf in server folder with nreco pdf generator.
You will need to set a regular path to your file system like e.g. "C:\temp\myfolder\". Or use a . instead of ~ and backslashes:
htmlToPdf.PdfToolPath = ".\\files\\";
If NReco is able to deliver you an byte-array or a stream you should prefer this instead of a file and return it directly.
UPDATE:
After takeing a look into the documentation of NReco all you need to do is following:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "<CORRECT_PATH_FOR_TOOL>";
var output = htmlToPdf.GeneratePdf(template);
System.IO.File.WriteAllBytes("<OUTPUT_PATH>", output);
This should create your pdf in the OUTPUT_PATH.
#OlaFW thanx for your effort.
I got my answer.
var pdfBytes = htmlToPdf.GeneratePdf(template);
string filePath = "/files/Myfile.pdf";
string Url = System.Web.Hosting.HostingEnvironment.MapPath(filePath);
System.IO.File.WriteAllBytes(Url, pdfBytes);

File Download using asp.net mvc

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);
}

how to get filename from URL in javascript

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("."));

base64 img src in WebUI leads to an error

Here is the problematic part of the template:
<ul id="list">
<template iterate='file in convertedfiles.files'>
<li>{{file.filename}}
<template if='file.isImage'>
<img src="{{file.src}}" alt="{{file.filename}}"><br/>
Source: {{file.src}}
</template>
</li>
</template>
</ul>
convertedfiles is a list of AndroidFile:
class AndroidFile {
File _file;
String filename;
String src;
bool isImage;
AndroidFile(this._file) : isImage = false {
filename = htmlEscape(_file.name);
// If the file is an image, read and display its thumbnail.
if (_file.type.startsWith('image')) {
FileReader reader = new FileReader();
reader.on.load.add((e) {
src = reader.result.toString().trim();
// prints the correct URL (data:image/png;base64,...)
print(src);
isImage = true;
watcher.dispatch();
});
reader.readAsDataUrl(_file);
}
}
}
The template gets displayed. It shows the filename, it shows the source but the imagetag looks like
<img alt="screenshot-1179.png" src="#">
The hash is underlined (in Chromium source view) and if I click on it it says "File not found: /web/out/"
Converted to JS is says in Chrome:
"Resource interpreted as Image but transferred with MIME type text/html"
Sample source is on GitHub
Any hints?
Note that if you know that you are handling a safe URI that is not vulnerable to XSS, you can work around this problem by using a SafeUri wrapper (imported from web_ui/web_ui.dart). For instance, change your template from:
<img src="{{file.src}}" alt="{{file.filename}}">
to:
<img src="{{new SafeUri.unsafe(file.src)}}" alt="{{file.filename}}">
Or change file.src internally to store a SafeUri.
I found the problem.
It's because the URI gets sanitized for security reasons. The sanitizer turns invalid URIs into a hash #.
From web_ui/templating.dart:
/**
* Ensure that [usiString] is a safe URI. Otherwise, return a '#' URL.
*
* The logic in this method was based on the GWT implementation located at:
* http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/safehtml/shared/UriUtils.java
*/
String sanitizeUri(uri) {
if (uri is SafeUri) return uri.toString();
uri = uri.toString();
return _isSafeUri(uri) ? uri : '#';
}
const _SAFE_SCHEMES = const ["http", "https", "ftp", "mailto"];
bool _isSafeUri(String uri) {
var scheme = new Uri(uri).scheme;
if (scheme == '') return true;
// There are two checks for mailto to correctly handle the Turkish locale.
// i -> to upper in Turkish locale -> İ
// I -> to lower in Turkish locale -> ı
// For details, see: http://www.i18nguy.com/unicode/turkish-i18n.html
return _SAFE_SCHEMES.contains(scheme.toLowerCase()) ||
"MAILTO" == scheme.toUpperCase();
}
So the sanitizer turns your data: scheme URI into a #. Data URIs can be used for XSS, but as far as I know the check could be improved by allowing data URIs when the data URI content type is image/*.
Perhaps file a bug report?

Image upload to filesystem in Grails

I'm implementing a file upload functionality to a web-app in Grails. This includes adapting existing code to allow multiple file extensions. In the code, I've implemented a boolean to verify that the file path exists, but I'm still getting a FileNotFoundException that /hubbub/images/testcommand/photo.gif (No such file or directory)
My upload code is
def rawUpload = {
def mpf = request.getFile("photo")
if (!mpf?.empty && mpf.size < 200*1024){
def type = mpf.contentType
String[] splitType = type.split("/")
boolean exists= new File("/hubbub/images/${params.userId}")
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
} else {
tempFile = new File("/hubbub/images/${params.userId}").mkdir()
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
}
}
I'm getting the exception message at
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
So, why is this error happening, as I'm simply collatating an valid existing path as well as a valid filename and extension?
Why do you think that convertation of File object to Boolean returns existence of a file?
Try
File dir = new File("/hubbub/images/${params.userId}")
if (!dir.exists()) {
assert dir.mkdirs()
}
mpf.transferTo(new File(dir, "picture.${splitType[1]}"))

Resources