Use "localhost" instead of "app://" to display files in TideSDK - javascript

Is there any way to load/display files by using 'localhost' address instead of 'app://'?
I mean something like:
http.://localhost/com.app/file.swf
I've tried using HTTPServer & FileStream listed on TideSDK documentation, but every time I try to load a file, the entire app gets blocked and stops responding.
server = Ti.Network.createHTTPServer();
//Specify port number and callback function
//This example can be tested by pointing your
//browser to http://localhost:8082/
server.bind(8082,'localhost',function(request,response) {
//Serve desired file
var contents,
contentType,
readFi = Ti.Filesystem.getFile(Ti.App.getHome()+'/flash',request.getURI());
if (readFi.exists())
{
var Stream = Ti.Filesystem.getFileStream(readFi);
Stream.open(Ti.Filesystem.MODE_READ);
contents =Stream.read();
Stream.close();
}
response.setContentType("application/x-shockwave-flash");
//Setting content length of the response
response.setContentLength(readFi.size());
//Setting status and reason
response.setStatusAndReason('200','OK');
//Finally writing the response back
response.write(contents);
});

Related

send file from node to client for download

I am using an ajax call from browser
so, on button click
a function is called
for route '/file'
app.get('/filez',function(req,res){
var id = req.params.id;
console.log('id is : ',id);
var video = ytdl(url, { filter: (format) => format.container === 'mp4' })
.pipe(fs.createWriteStream('video.mp4'));
res.download('video.mp4');
now, the file is being downloaded to the server at the moment.
but what I want to do is to send the file so the client can download it from browser.
i dont want the file to be downloaded to the server.
Here's the ajax request I made from the browser using a button click.
and I want to get the file as the response which can be downloaded to the client computer.
function myAjaxCall(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState ===XMLHttpRequest.DONE && xhr.status ===200){
console.log('response has come',xhr.response);
return xhr.response;
}
};
xhr.open('GET','/filez',true);
xhr.send();
};
EXPLANATION : well, not really. i was thinking more along these lines - so on button click an ajax call is sent to server and it's supposed to get back a response. I want the file to be sent via this response.
so, how do I accomplish this?
pass the get request in a href tag and it will download the file to the client , you are writing the file in server side so it is being created their , you have to have the file been created on the server side and then serve the file through res.download to the client side and later delete the file from the server side to download the file in clinet side
suppose your url looks like http://getsomefile.com/xyz?newfile=video.mp4 then in your client sides a tag you can have this url as on some domain http://getsomefile.com with route xyz to serve the file
<a href="http://getsomefile.com/xyz?newfile=video.mp4" download>
where i am assuming on client side you have some route defined as
app.get('/xyz,function(req,res){
var file = req.query.newfile;
})
and then you can use fs.unlink to delete the files through a cron like or have a manual cleaner used or do something like this
app.get('/xyz', function(req, res){
var file = req.query.newfile
res.download(realFilepath, file , function(err) {
if (!err) {
fs.unlink(realFilepath);
}
});
});
realFilepath is the actual path of file kept in server , which you can gracefully delete after the file has been served.

Split video file to stream from browser

I split a video file into two using the split-file module.
There are no file part extensions. They seem like: gan-1, gan-2
I am hosting these two files on my own server.
http://bilketay.com/download/gan-1
http://bilketay.com/download/gan-2
I try to stream these two files through the browser like a single video file. Like;
// Dependencies
var express = require('express');
var app = express();
var CombinedStream = require('combined-stream2');
var request = require('request');
// Some routes
app.get('/', function(req, res) {
// Set header
res.set({
"Content-Type": 'video/mp4'
});
res.writeHead(200);
var combinedStream = CombinedStream.create();
// This function is to call gan-1 first, then gan-2
var recursive = function(param) {
var req = request('http://bilketay.com/download/' + param);
// First add gan-1, then gan-2
combinedStream.append(req);
req.on('end', function() {
if (param != 'gan-2') {
recursive('gan-2')
}
});
}
// Start recursive
recursive('gan-1');
// Start stream browser
// But, It does not start until it is completely loaded :(
combinedStream.pipe(res);
});
// Listen port
app.listen(3000);
I created this code with restricted node.js information. No problem for me, but I think Google Chrome is different. :)
The problem is, the two parts do not stream without being loaded. The stream starts after two parts have been uploaded. What I want to do is start the stream right away. A short note; gan-1 and gan-2 files are working locally. But it does not work on the remote server. What am I doing wrong?
I used the combined-stream2 module to merge the parts.
This module simplifies streaming by adding two different files. But because I can not get the result I want, I might have used it wrong.
In short, I want to stream two different files through the browser, respectively.
I need the help of ninjas. Thank you.
Screen shot describing the problem;
stream.gif

File copying using NodeJS

I am trying to copy a file from one location to another location. Here is my code below and I am calling this script like [1] http://localhost:8000/prdcopy/acbd.pdf
var http = require('http');
var fs = require('fs');
var express=require('express');
var app=express();
var path_upload = "/234.567.890.123/";
var path_prodn = "//123.345.678.999/sample/temp/";
app.get('/prdcopy/:file',function(req,res){
var rstream = fs.createReadStream(path_upload + req.params.file);
var wstream = fs.createWriteStream(path_prodn + req.params.file);
rstream.pipe(wstream);
res.end();
rstream.on('end', function () {
console.log('SrcFile');
});
wstream.on('close', function () {
console.log('Done!');
});
});
var server=app.listen(8000,function(){
console.log("listening on port 8000...");
});
It copies the file properly however after copying the Firefox browser opens up a PDF reader. There is no file loaded in it though. This is my first node script and I would like to know what is that I am doing wrong. In IE it is not opening any PDF Reader window.
This is not necessarily an error.
With res.end() you are sending back an http response with no Content-Type header. What Firefox does in this case is detecting the .pdf at the end of the typed URL and assuming that the response will contain something that is displayable by the PDF viewer. This is not the case as you are not sending anything back (no body).
Try substituting res.end() with something like:
res.header("Content-Type", "text/html");
res.end();
You will see that no PDF viewever is displayed even in Firefox. You could also use other res methods that automatically set the content type for you. For instance, to send a json response back substitute res.end() with:
status = {};
status.message = "Copied successfully";
res.json(status);

How to set the name of a file in jquery

(This title may not be clear but whatever you read here is a refinement trying to get past the "quality standards" script, which seem to be a lot stricter based on the tags chosen)
On the client side is there any way in jquery to set the name of the file downloaded?
lets say on my server the file is stored as QXYZO123 , but the file is really information.xls , a spreadsheet. Even the hyperlink says information.xls as I have information linking the random file name to the original file name.
When the user clicks on the link, by default it will try to download the file name as stored on the server, QXYZO123, but I want it instead to say information.xls , how can I set this to suggest the file name to save as?
I call it a suggestion because based on the user's browser settings, it will either auto download with my filename suggestion or ask the user where to download and save it, with the filename suggestion
There is no setting file properties from JQuery directly. JQuery means some Javascript codes and Javascript is a client side script language. This means you can do something, only on client side, not on server side.
But there is some indirect methods to do this. First of all, only way to do this is setting the file name on server side. It depends on what language you are using on server side. Depens on server side language, You can write your own download web api. Pass the file name as a request parameter to your api and let it give you the file with your customized file name. I don't know what language you are using on server side but I prepared a serverside code with node.js that accepts customized file name in 'GET' request as parameter.
var sys = require ('sys'),
url = require('url'),
http = require('http'),
qs = require('querystring');
var path = require('path');
var mime = require('mime');
var fs = require('fs');
var server=http.createServer(
function (request, response) {
if(request.method=='GET') {
var filePath='path_to_your_file_in_your_server_file_system';
var filestream = fs.createReadStream(filePath);
var url_parts = url.parse(request.url,true);
console.log(url_parts);
var fileName= url_parts.query.fileName; //Taking your customized file name from GET request parameters.
if(!fileName)
{
fileName=path.basename(filePath);
}
var mimetype = mime.lookup(filePath);
response.setHeader('Content-disposition', 'attachment; filename=' + fileName);
response.setHeader('Content-type', mimetype);
filestream.pipe(response);
response.writeHead( 200 );
response.end();
}
}
);
server.listen( 9080 );
When you run this server code with node.js you can get file with your customized file name from the url which localhost:9080?fileName=yourCustomizedFileName. As you see we are giving the fileName 'GET' request parameter in url. You can use javascript windows.location or something else to get the file with your customized file name on client side Javascript code.
Don't let the node.js code make you confused. The point of the solution is writing a downloading api which takes fileName parameter from 'GET' request, to send the file with this name to clients.
You can apply this node.js code for your server side language or research how to apply it. Probably, It won't be hard to find and apply it.

Sending client side form input to server side database query via Node.js and return results to client

I am developing a web application where the user can type in a "device id" on the web page (we have 100's of devices out on the field in production use each with a unique ID), that result entered by the user will be sent to the Node.js server that in return will store it into a variable and use it in a SQL Query to retrieve results about that particular device from the database server and then display the results back to the client web page.
Currently the form input feature has not been implemented yet even though I've already coded the form code in html.
The program works fine as it is if I were to manually change the DEVICE_ID to the device I wish to retrieve data from in the code but of course I want to be able to enter this on the client page instead of me having to change it in the server-side source code manually.
"use strict";
var pg = require('pg').native;
var http = require('http');
var $ = require('cheerio');
var fs = require('fs');
var url = require('url');
var htmlString = fs.readFileSync('index.html').toString();
var parsedHTML = $.load(htmlString);
var dbUrl = "tcp://URL HERE/";
// The Sign-ID
var DEVICE_ID = '2001202';
// Create the http server
http.createServer(function (request, response) {
var request = url.parse(request.url, true);
var action = request.pathname;
// Connect and query the database
pg.connect(dbUrl, function(err, client) {
// The complete sql query for everything that's needed for the app!
client.query("SQL QUERY IS HERE" + DEVICE_ID + "etc..",
function (err, result) {
// Remaining program code is here that performs DOM based
// manipulation to display results returned from the server
// to the client side page.
// Time to Render the document and output to the console
console.log(parsedHTML.html());
// Render the document and project onto browser
response.end(parsedHTML.html());
}
); // End client.query
}); // End pg.connect
}).listen(8080); // End http.CreateServer
pg.end();
I've considered the following:
1) Use An OnClick() function from within the HTML code, like this:
onclick="lookupSignID()
Then include an external JS file from within the HTML that includes the lookupSignID() function however I soon found out this is only performing client-side function and is not what I want.
2) AJAX is only good for if the server is generating new information by itself, therefore I can't use AJAX since the user is entering the device ID to get information from it.
3) Possibly using POST/ GET
Can anyone please advise on what course of action I should take? If solution (3) is the best way how would I go about doing this? Can it be integrated into my existed code (shown above) without many changes?
Thanks!
If you used jQuery on the client side with an AJAX POST function, and then on the server side, you have express.js, you could do this:
app.post('/deviceid', function(req, res) {
var deviceid = req.param('deviceid')
console.log(deviceid)
...
})

Categories

Resources