Calling shared drive folder using javascript - javascript

I have two servers: A and B.
My Classic ASP application is deployed on Server A.
Server B contains a Folder (ScannedDocuments). I have created a Shared Drive on Server A to point to this folder. The Share Drive is named Q:.
On IE 7, when I try to access file using javascript, I am using:
window.open(file://Q:/a.txt)
It opens the file. But on IE 8 and above and all versions of Firefox, it is not opening. Neither an error is generated nor the file is opening.
I guess it is getting blocked by browser's security features.
Please let me know how I can open files on these browser versions.
Is there any other way to open a remote file using javascript or using IIS?
** Edited **
I tried creating a Virtual Directory on IIS and pointing to Shared Drive. But it gives error: resource or directory not found.
I am using IIS 7

#Anant Dabhi is right - create simple Ajax call to server ant return file content.
Client (JS). Use it instead of window.open(file://Q:/a.txt)
function getFile(filename) {
$.ajax({
url: "/YourWeb/File/Get",
data: {
filename: filename
},
success: function (data) {
console.log(data);
}
});
}
Your "backend". Assume that your are using .NET :)
public ActionResult Get()
{
string pathToFolder = "x:\\yyy\\zzz";
// Strip any directories and leave only name of file. Exception is possible ;)
string filename = Path.GetFileName(Request["filename"]);
byte[] ba = File.ReadAllBytes(Path.Combine(pathToFolder, filename));
string s = Encoding.UTF8.GetString(ba);
// Return as text (if you are absolutetlly sure it is text!)
return Content(s);
// Or pack it in JSON object to have status
return Json(new { Status = true, Data = s });
}
You could connect to UNC if you wish https://msdn.microsoft.com/en-us/library/windows/desktop/aa385482%28v=vs.85%29.aspx

Related

How do I use a downloaded svg file within my application using Tizen Web studio?

I can get an SVG file downloaded, additionally, I can display svg files as you would normally within an image tag. I do not know how to access the folder location for downloads or the wgt-private folder so I may download images to a client's watch and then use the downloaded version.
I'm sure my file is downloading as I've console logged on successful download and when I list the items in the directory the file shows up.
Placing downloads/[filename] or wgt-private/[filename] does not appear to work as these are virtual file locations however I've no idea how to access these files within the application without using the filesystem methods.
Download:
var download_obj = new tizen.DownloadRequest('someFile.svg', 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
onprogress: function(id, receivedSize, totalSize) {
console.log(id);
console.log(receivedSize);
console.log(totalSize);
},
onpaused: function(id) {
console.log(id);
},
oncanceled: function(id) {
console.log(id);
},
oncompleted: function(id, fullPath) {
console.log(id);
console.log(fullPath);
},
onfailed: function(id, error) {
console.log(id);
console.log(JSON.stringify(error));
}
});
Full path comes out as: wgt-private/someFile.svg
Doesn't display as displays a file error in the console on all attempts.
I understand that your questions relates to how to show the image downloaded with tizen.download API in html img tag.
I can see two workarounds that could help you with it:
You can use filesystem API (which you would like to avoid), BUT since 5.0 there is a method which needs no additional privileges and I hope it will match your needs - FileSystemManager.toURI(). It just gets the path to file (returned by download API) and returns the full URI, able to be used in img.
I noticed that download to non-public directories on the device, download API returns the 'hidden' path which uses virtual root, but when downloading to public directory as 'downloads', the full path is returned and it works for img as well.
If both of above is not acceptable for you, I am afraid that the only alternative is to use regular tizen.filesystem API and resolve the path from download API and then use File.toURI() function to get the path.
var link = "http://techslides.com/demos/samples/sample.jpg"
var download_obj = new tizen.DownloadRequest(link, 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
oncompleted: function(id, fullPath) {
console.log("completed " + id + " : " + fullPath);
tizen.filesystem.resolve(fullPath, (s)=>{console.log("Resovled full path: " + s.toURI())}, (e) => {console.log(e)})
},
onfailed: function(id, error) {
console.log("failed " + id);
console.log(JSON.stringify(error));
}
});
You can find the proper web sample app: new Tizen project - Sample - Mobile 4.0 - Web application - Content - Download Manager
Open index.html and replace https://www.sample-videos.com/video/mkv/720/big_buck_bunny_720p_10mb.mkv with your file address.

Generate and download archive zip with java

I have a zip file download function.
This function generates the .zip files on output folder in the server and downloads it.
Everything works perfectly!
However, testing with multi-users doens't work.
If 3 users attempt to generate the file at the same time, only one response is returned with the file for download.
The other 2 users are waiting forever and there is no result (no error occurs, the ajax call never returns).
My code:
JavaScript:
$.fileDownload('\GenereteZipAction', {
httpMethod: "POST",
data: $('#formZip').serialize()
}).done(function () {
alert('Download successfully.');
$('#modalZipLoading').modal('hide');
})
.fail(function () {
alert('Error');
$('#modalZipLoading').modal('hide');
});
Java:
//get the name of user
userName = request.getParameter("user");
//get real path
String realPath = getServletContext().getRealPath("/");
//create user folder
File fileOutput = new File(realPath+"/reports/output/"+userName);
fileOutput.mkdirs();
//generete reports in the user output folder
ReportHelper helper = new ReportHelper();
helper.genereteReports(fileOutput);
//set the reponse and...
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment;filename=Relatorios.zip");
//set the cookie for $.fileDownload go to done function
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
//zip output user folder
ZipHelper zipHelper = new ZipHelper ();
zipHelper.zipAllfiles(fileOutput);
//create and fill ZipOutputStream
ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
zipHelper.fillZipOutputStream(zip);
//do download
zip.flush();
//close
zip.close();
//delete folder
deleteDir(fileOutput);
My system is for more than five thousand users, so I'm sure more than two will use the report generation function at the same time.
I do not have much information of aplication server, just know it is IBM WebSphere.
I do not know if the problem is in my code, or the server that
not allowing multi-users. Every help is welcome!!!
You are most likely running into thread safety issues. This may help you: https://www.quora.com/What-does-the-term-thread-safe-mean-in-Java
ReportHelper or ZipHelper could be not thread-safe. genereteReports looks to be modifying something on the file system. I would look carefully at the code and ask yourself on each line, "what happens if something else tries to execute while my first thread is executing this line?" I would suggest looking into synchronized calls and how they work.

How do I return a file to the user?

I am trying to return a file to the user.
"GetExcel" appears to work and in debug I can see that "ba" has data.
The method completes BUT nothing appears to be returned to the browser - I am hoping to see the file download dialog.
C#
public FileResult GetExcel()
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells["A1"].Value = "LBHERE";
var ba = pck.GetAsByteArray();
return File(ba, "text/plain", "testFile.txt");
}
}
Javascript
function clickedTest() {
alert("Test clicked");
$.get(myPath + "/Employee/GetExcel", { }, function (data) {
})
};
jQuery's $.get() function pulls data from a webpage into your client-side scripts through AJAX. This is not what you want to do if you want to download a file. Instead, you should open a new tab set to the URL of the file you wish to download.
Try this:
function clickedTest() {
window.open(myPath + "/Employee/GetExcel", "_blank");
}
If your browser still isn't initiating a download, but is instead just displaying a file, you may have to go one step further.
Somewhere in your server-side code, when you have access to the Response object, you should set the Content-Disposition header to attachment and provide a filename for the spreadsheet you are serving. This will inform your browser that the file you are requesting is meant to be downloaded, not displayed.
This can be done as follows:
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.xls")
Of course, replace myfile.xls with the proper filename for your spreadsheet.

Installing firefox extension on a web site

I have created an extension for mozilla firefox. Now, I'm trying to distribute the extension on an simple web site. I generate a sha1 hash code from an online generator. This is the code I have in my web site:
<script type="application/javascript">
function install (aEvent)
{
for (var a = aEvent.target; a.href === undefined;) a = a.parentNode;
var params = {
"Foo": { URL: aEvent.target.href,
Hash: aEvent.target.getAttribute("hash"),
toString: function () { return this.URL; }
}
};
InstallTrigger.install(params);
return false;
}
</script>
<a href="c:/grouAndUsersWorkSpace/MozillaAddon/createtab.xpi"
hash="sha1:a7093a2afe1a53fde114a4a7dcb3e15e57862642"
onclick="return install(event);">Install Extension!</a>
the path of the url is local. And as a result when I start the application I got "The add-on could not be downloaded because of a connection failure on localhost".
I changed the path of the url to be: file://c:/grouAndUsersWorkSpace/MozillaAddon/createtab.xpi and with this nothing happens.
I have two questions:
1. Is that a good way to generate a hash code?
2. What should cause that connection failure?
1) I prefer to use the CHK Checksum Utility to generate checksums.
2) I don't have access at the moment to verify it, but have you tried serving the extension with Apache or similar?
Edit
Since you used a local file, you'll need a 3 slashes instead of 2 : file URI scheme .
Tested it both ways, they both work.

How to fetch file content (basically read) a local file in javascript for UIAutomation iOS

Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).

Categories

Resources