Download file: ACCESS DENIED - javascript

I keep on having "ACCESS DENIED" after hitting my download button.
I already have full control on the specified folder.
I use this in jquery.
function DownloadFile(ProductNumber, File)
{
var windowSizeArray = ["width=400,height=400",
"width=500,height=600,scrollbars=yes"];
File = "C:/Documents and Settings/My PC/My Documents/" + File;
if (File != "")
{
var windowName = "popUp";
var windowSize = windowSizeArray[$(this).attr("rel")];
var exist = isExists(File);
if (exist)
{
window.open(File, windowName, windowSize);
}
else
{
ShowAlertMessage("The file for Product no. <a href='" + File + "' target='blank'>" + ProductNumber+ "</a> does not exist.");
}
}
else
{
ShowAlertMessage("No PDF file for Product no: " + ProductNumber+ ".");
}
}

You can't access local files like you do in your snippet.
You have to upload the file to the server and use PHP/another serverside language to do that. jQuery (or Javascript) only runs in the browser and does not have access to files outside it. Serverside web-languages only have access to files located on the server (or other servers using get_file_contents or cURL).
Your code looks like a C#/Java-source. They can access these local files.

Related

Saving a file in a UWP web context

I recently developed a universal application for Windows 10 with UWP web context (so JavaScript and HTML) and I would like to save a text file. It works well on a browser (Chrome, Firefox, Edge,...) but not in the application.
Can someone help me? :)
Thank you in advance!
Here is the code responsible for saving the text file.
function saveTextAsFile(fileName) {
var source = input.value.replace(/\n/g, "\r\n");
var fileUrl = window.URL.createObjectURL(new Blob([source], {type:"text/plain"}));
var downloadLink = createDownloadLink(fileUrl, fileName);
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);}
To download a file using a Progressive Web App as a Universal Windows Platform you can use the Windows global object with the FileSavePicker. Note that you can check to see if it exists using if (window['Windows'] != null) { ... }
// Create the picker object and set options
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.fileTypeChoices.insert("Plain Text", [".txt"]);
// Default file name if the user does not type one in or select a file to replace
savePicker.suggestedFileName = "New Document";
savePicker.pickSaveFileAsync().then(function (file) {
if (file) {
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.deferUpdates(file);
// write to file
Windows.Storage.FileIO.writeTextAsync(file, fileContents).done(function () {
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.CachedFileManager.completeUpdatesAsync(file).done(function (updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
WinJS.log && WinJS.log("File " + file.name + " was saved.", "sample", "status");
} else {
WinJS.log && WinJS.log("File " + file.name + " couldn't be saved.", "sample", "status");
}
});
});
} else {
WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
}
});
This assumes you are downloading a text file. To download a Uint8Array use the WriteBytesAsync function on FileIO instead. Note that many of the functions on FileIO are available in JavaScript even though they are not documented for JavaScript.
Check out the FileSavePicker Class documentation for more information.

WebRTC issue with File transfer in production application

Hello I am developing a WebRTC based file transfer application.I have deployed the application online using Heroku. But there seems to be a problem with file transfer specifically at the the receiving end which I have been unable to figure out. The file is transferred and received successfully when done on localhost but there is a problem with file reception when done in production. The browser used is Google Chrome if that's any help.
Here is the File reception code:
function dataChannelStateChanged() {
if (dataChannel.readyState === 'open') {
console.log("Data Channel open");
dataChannel.onmessage = receiveDataChannelMessage;
}
}
function receiveDataChannel(event) {
console.log("Receiving a data channel");
dataChannel = event.channel;
dataChannel.onmessage = receiveDataChannelMessage;
}
function receiveDataChannelMessage(event) {
console.log("From DataChannel: " + event.data);
if (fileTransferring) {
//Now here is the file handling code:
fileBuffer.push(event.data);
fileSize += event.data.byteLength;
fileProgress.value = fileSize;
//Provide link to downloadable file when complete
if (fileSize === receivedFileSize) {
var received = new window.Blob(fileBuffer);
fileBuffer = [];
downloadLink.href = URL.createObjectURL(received);
downloadLink.download = receivedFileName;
downloadLink.appendChild(document.createTextNode(receivedFileName + "(" + fileSize + ") bytes"));
fileTransferring = false;
//Also put the file in the text chat area
var linkTag = document.createElement('a');
linkTag.href = URL.createObjectURL(received);
linkTag.download = receivedFileName;
linkTag.appendChild(document.createTextNode(receivedFileName));
var div = document.createElement('div');
div.className = 'message-out';
div.appendChild(linkTag);
messageHolder.appendChild(div);
}
}
else {
appendChatMessage(event.data, 'message-out');
}
}
The following image shows the problem i'm encountering when receiving the file:
Any guidance would be much appreciated.
WEBRTC is based on UDP, it means there is no guarantee that your sequence of data transfers "in order" or successfully
use "webSocket" or a simple "http request" instead.
=============
UPDATE: see the first comment

how to open a file in javascript with multiple extensions?

I am facing a small issue here...
I want to write a javascript function to open files with different extensions, I have already written a function that can open files but with their extensions hard written in the code, how to make this dynamic? Like Instead of opening "file1.pdf" or "file1.png" I want to store the extension as a variable and open it dynamically.
Here is the code:-
<script>
function viewCM() {
var transferID = document.getElementById("theTransferID").value;
$.get("/Uploads/" + transferID + ".pdf")
.done(function () {
// Do something now you know the file exists.
window.open("/Uploads/" + transferID + ".pdf", '_blank', 'fullscreen=yes');
}).fail(function () {
// File doesn't exist - do something else.
alert("File was not found");
})
return true;
}
</script>
The above function works perfectly with any type of extension but I can't manage to know how to make the extension dynamic
Thanks in advance
EDIT: I don't get the file name from the server, The idea is simply that I have an upload button that uploads a file related to a specific "transfer" and I make the name of the uploaded file as transferID.whatever extension then when I want to open the file, I just write the code I posted. so I don't search the server for the file name.
Following up on comments in the original question:
function viewCM(fileExtension) {
var transferID = document.getElementById("theTransferID").value;
$.get("/Uploads/" + transferID + "." + fileExtension)
.done(function () {
// Do something now you know the file exists.
window.open("/Uploads/" + transferID + "." + fileExtension, '_blank', 'fullscreen=yes');
}).fail(function () {
// File doesn't exist - do something else.
alert("File was not found");
})
return true;
}
You should not need to have any if statements within viewCM() if you can pass the file extension to the function (unless you're planning on performing some type of validation).
It will automatically adjust according to file type.
means if pdf then open pdf viewer, excel should open excel
window.open( file Name );
Maybe you could find whats after the dot in the name to search for the type, just an idea.
var afterDot = str.substr(str.indexOf('.'));
Then depending on type do your code.
(This can be very much improved).
EDITED:
var transferID = document.getElementById("theTransferID").value;
var extension = transferID.substr(transferID.indexOf('.'));
Now you have this possibility:
if(extension == ".pdf"){ $.get("/Uploads/" + transferID + ".pdf")
.done(function () {//...}
For anyone facing the same issue, I have made a some kind of "naive" workaround to solve this by making multiple JavaScript functions to open various types of files.
It is as simple as : try to read a pdf file, if you can't then call a function that reads a png file etc!!
<script>
function viewCM() {
var transferID = document.getElementById("theTransferID").value;
$.get("/Uploads/" + transferID + ".pdf")
.done(function () {
// Do something now you know the file exists.
window.open("/Uploads/" + transferID + ".pdf", '_blank', 'fullscreen=yes');
}).fail(function () {
// File doesn't exist - call the next function.
viewCMPng();
})
return true;
}
function viewCMPng() {
var transferID = document.getElementById("theTransferID").value;
$.get("/Uploads/" + transferID + ".png")
.done(function () {
// Do something now you know the file exists.
window.open("/Uploads/" + transferID + ".png", '_blank', 'fullscreen=yes');
}).fail(function () {
// File doesn't exist - show alert message.
alert("File was not found");
})
return true;
}
</script>

how do I remove an item that is set to upload?

I have created an uploader using javascript and php. The problem is that I only want to allow specific file types. I have it letting the user know the file is not valid but I am not sure how to remove the file from being uploaded. Can anyone tell me how to remove the upload?
multiUploader.prototype._preview = function(data) {
this.items = data;
if (this.items.length > 0) {
var html = "";
var uId = "";
for (var i = 0; i < this.items.length; i++) {
uId = this.items[i].name._unique();
if (typeof this.items[i] != undefined) {
if (self._validate(this.items[i].type) <= 0) {
var errorClass = '<h3 class="text-danger">Invalid file format' + this.items[i].name + '</h3>'
jQuery(".errorContent").append(errorClass);
jQuery.remove(this.items[i]);
}
html += '<div class="dfiles" rel="' + uId + '"><h5>' + this.items[i].name + '</h5><div id="' + uId + '" class="progress" style="display:none;"></div></div>';
}
}
jQuery("#dragAndDropFiles").append(html);
}
}
This is not all of the code, just the function that displays my error message and also shows the uploaded file on the page. I tried it with jQuery.remove but it does not work. Any ideas are appreciated
what is a "file type"? I could send you a .php file that ends in .jpg, would you accept that? (I hope not!). Let the user upload the files with a warning that files X, Y, Z are not going to be accepted based on extension mismatch. Then actually test their content to see if the files are truly what their extension claims, because -and this part is important- your javascript in no way guarantees that what you're going to get is what you wrote your scripts to allow. Changing your script in my browser is a matter of opening my devtools and rewriting your script, then hitting ctrl-s. Now my browser will be running my code, not your code, and happily upload my files anyway.
Always, always, server-verify the user data.

How to save the current webpage with casperjs/phantomjs?

Is there a way to save the current webpage by using casperjs or phantomjs?
I tried to get the html and save it into a file. But the resulting file was a lot different from the screenshot of that time (with casper.capture). Is there a way to save the current webpage?
Andrey Borisko suggested to use the disk cache to retrieve the resources. My solution is not that efficient, but you don't need to decompress text files.
I use XMLHttpRequest to retrieve all resources after I registered them with the resource.received event handler. I then filter the resources into images, css and fonts. The current limitation is that remote resource paths that contain something like ../ or ./ are not handled correctly.
I retrieve the current page content with getHTML and iterate over all captured resources to replace the path used in the markup, that is identified by a portion of the complete resource URL, with a randomly generated file name. The file extension is created from the content type of the resource. It is converted using mimeType from this gist.
Since CSS files may contain background images or fonts, they have to be processed before saving to disk. The provided loadResource function loads the resource, but does not save it.
Since XMLHttpRequest to download the resources the script has to be invoked with the --web-security=false flag:
casperjs script.js --web-security=false
script.js
var casper = require("casper").create();
var utils = require('utils');
var fs = require('fs');
var mimetype = require('./mimetype'); // URL provided below
var cssResources = [];
var imgResources = [];
var fontResources = [];
var resourceDirectory = "resources";
var debug = false;
fs.removeTree(resourceDirectory);
casper.on("remote.message", function(msg){
this.echo("remote.msg: " + msg);
});
casper.on("resource.error", function(resourceError){
this.echo("res.err: " + JSON.stringify(resourceError));
});
casper.on("page.error", function(pageError){
this.echo("page.err: " + JSON.stringify(pageError));
});
casper.on("downloaded.file", function(targetPath){
if (debug) this.echo("dl.file: " + targetPath);
});
casper.on("resource.received", function(resource){
// don't try to download data:* URI and only use stage == "end"
if (resource.url.indexOf("data:") != 0 && resource.stage == "end") {
if (resource.contentType == "text/css") {
cssResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("image/") == 0) {
imgResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("application/x-font-") == 0) {
fontResources.push({obj: resource, file: false});
}
}
});
// based on http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource = function loadResource(url, method, data) {
"use strict";
this.checkStarted();
var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
return cu.decode(this.base64encode(url, method, data));
};
function escapeRegExp(string) {
// from https://stackoverflow.com/a/1144788/1816580
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(find, replace, str) {
// from https://stackoverflow.com/a/1144788/1816580
return str.replace(find, replace);
}
var wrapFunctions = [
function wrapQuot1(s){
return '"' + s + '"';
},
function wrapQuot2(s){
return "'" + s + "'";
},
function csswrap(s){
return '(' + s + ')';
}
];
function findAndReplace(doc, resources, resourcesReplacer) {
// change page on the fly
resources.forEach(function(resource){
var url = resource.obj.url;
// don't download again
if (!resource.file) {
// set random filename and download it **or** call further processing which in turn will load ans write to disk
resource.file = resourceDirectory+"/"+Math.random().toString(36).slice(2)+"."+mimetype.ext[resource.obj.contentType];
if (typeof resourcesReplacer != "function") {
if (debug) casper.echo("download resource (" + resource.obj.contentType + "): " + url + " to " + resource.file);
casper.download(url, resource.file, "GET");
} else {
resourcesReplacer(resource);
}
}
wrapFunctions.forEach(function(wrap){
// test the resource url (growing from the back) with a string in the document
var lastURL;
var lastRegExp;
var subURL;
// min length is 4 characters
for(var i = 0; i < url.length-5; i++) {
subURL = url.substring(i);
lastRegExp = new RegExp(escapeRegExp(wrap(subURL)), "g");
if (doc.match(lastRegExp)) {
lastURL = subURL;
break;
}
}
if (lastURL) {
if (debug) casper.echo("replace " + lastURL + " with " + resource.file);
doc = replaceAll(lastRegExp, wrap(resource.file), doc);
}
});
});
return doc;
}
function capturePage(){
// remove all <script> and <base> tags
this.evaluate(function(){
Array.prototype.forEach.call(document.querySelectorAll("script"), function(scr){
scr.parentNode.removeChild(scr);
});
Array.prototype.forEach.call(document.querySelectorAll("base"), function(scr){
scr.parentNode.removeChild(scr);
});
});
// TODO: remove all event handlers in html
var page = this.getHTML();
page = findAndReplace(page, imgResources);
page = findAndReplace(page, cssResources, function(cssResource){
var css = casper.loadResource(cssResource.obj.url, "GET");
css = findAndReplace(css, imgResources);
css = findAndReplace(css, fontResources);
fs.write(cssResource.file, css, "wb");
});
fs.write("page.html", page, "wb");
}
casper.start("http://www.themarysue.com/").wait(3000).then(capturePage).run(function(){
this.echo("DONE");
this.exit();
});
The magic happens in findAndReplace. capturePage is completely synchronous so it can be dropped anywhere without much head ache.
URL for mimetype.js
No, I don't think there is an easy way to do this as phantomjs doesn't support rendering pages in mht format (Render as a .mht file #10117). I believe that's what you wanted.
So, it needs some work to accomplish this. I did something similar, but i was doing it the other way around I had a rendered html code that I was rendering into image/pdf through phantomjs. I had to clean the file first and it worked fine for me.
So, what I think you need to do is:
strip all js calls, like script tags or onload attributes, etc..
if you have access from local to the resources like css, images and so on (and you don't need authentication to that domain where you grab the page) than you need to change relative paths of src attributes to absolute to load images/etc.
if you don't have access to the resources when you open the page then I think you need to implement similar script to download those resources at the time phantomjs loads the page and then redirect src attributes to that folder or maybe use data uri.
You might need to change links in css files as well.
This will bring up the images\fonts and styling you are missing currently.
I'm sure there are more points. I'll update the answer if you need more info, once I see my code.

Categories

Resources