Plupload filename problem - javascript

I ask here in the hope that some members will be familiar enough with 'plupload' to help.
This little Jquery script is on the way to making my file-upload problems go away, so any help would be greatly appreciated.
Question:
I can upload large files using plupload, but when the appear on the server the name has changed to gibberish,
EG p163g1k1er15n310bi18bq1af61rc21.zip
From my experience with basic upload forms my assumption is that it is writing out a temp filename with the intention of renaming it to the original filename when the chunked sections have been put back together, but for some reason it may not be doing this.
I have changed the permission on the folder to 777, so I'm reasonably sure this isn't the issue.
The runtime being used is Flash (I require the chunking feature). It's version 1.4.3.2
As always, any help would be much appreciated.

There is a configuration option to generate unique file names instead of using the actual file name.
From the docs:
unique_names
Generate unique filenames when uploading. This will generate unqiue
filenames for the files so that they
don't for example collide with
existing ones on the server.
Make sure this option is not enabled in your configuration (it is not by default). There are still some file name cleaning routines run by the default included php upload script...
// Clean the fileName for security reasons
$fileName = preg_replace('/[^\w\._]+/', '', $fileName);
...and an underscore is always appended with a number if the file exists (regardless of configuration), like filename_2.jpg, but aside from that it should not be altering your file names.
EDIT: I've been searching the forums for a solution but coming up short, my last piece of advice is to try the HTML5 runtime, to see if this is related to the Flash runtime somehow, as there have been some issues with previous versions. If all else fails, post on the forum - the admins there are very responsive. Best of luck, please post a solution here if you find it.

Ploploader uses a variable called "unique_names"; in my case this was set to TRUE, however to preserve the actual filenames it should be set to false. Solution came from the Pluploader forum.

To keep original filename, if you use the upload.php provided by plupload then I had to change upload.php line 34 from
$fileName = isset($_REQUEST['name']) ? $_REQUEST['name'] : '';
to
$fileName = isset($_FILES['file']["name"]) ? $_FILES['file']["name"] : '';

I had the same problem. An another solution is to inject real file name as a new input into FormData object.
(I am using chrome and HTML5 runtime!)
in plupload.html5.js file find the creation of object O = new FormData();
and
add some injections with
var oFileName = $("input[name='oFileName']").val();
O.append("oFileName", V.name);
After this adding get the real file name in your server side (for upload.php)
$oFileName = $_REQUEST["oFileName"];

Related

How to automatically make array of all files in website folder?

Let's say I have a folder of about 100 images on my website called "IMG"
Now let's say I have a div element: <div id="templateDiv"></div>
Using javascript, how would I add all images from "IMG/" into that div without adding <img src="IMG/IMGNAME.jpg"> for every image?
Sorry, I'm not very good at explaining.
Just ignore the fact that would take ages to load.
EDIT
Ok my bad explanation skills have made me change my question.
How do I automatically make array of all files in website directory?
Okay, your question is incredibly unclear, but from reading all your other comments and things, it seems you simply want to get an array that contains the filename of every file in a directory? If that's what you want, then it won't be possible (I don't believe) since only the server knows which files are where, and you can't request the contents of a directory from a server using JavaScript.
However if you were using Node.js on a local directory, then it could be done. But I don't believe that's your case.
That being said, you have three alternative options:
Name every image file 1.png, 2.png, 3.png, etc. Then use a for loop and get each one using (i + 1) + ".png"
If you can't rename the files, but the files are named via user input, you could collect the user's input at the time of file creation and add the name of the newly created file into another file/an array/localStorage so that it could be retrieved later.
If you can't rename the files, but the filenames are also never known to the program that needs them, then you could create an array of all the filenames (manually) and iterate over that to find all the files that you want.
Please, somebody let me know if I'm wrong and if there actually is a way to make a request to a server that tells the client all the files in a directory. That seems incredibly unlikely though.
Another potential solution just came to mind. You could write a PHP script (or Node.js or any server-side language, really) that scans a directory, creates a list of all the filenames there, and then sends that back over HTTP. Then you could simply make an XMLHttpRequest to that PHP file and have it do the work. How does that sound?

What does the "?" sign mean in a request for a static JS file?

I've seen that a lot and I just don't know what it means. This, for example:
<script src="http://server.com/file.js?y=2345678" type="text/javascript"></script>
If it is in deed possible to 'catch' the value of 'y' in the javascript file, how would that be?
Thank you.
PS. I know what mod_rewrite is and that is not the answer, just in case :)
This is to force the browser not to cache the file, by making it believe that it is a dynamic file with get parameter rather than a static one.
This is often used to facilitate caching of the JS file. You set a far-future Expires header which means the browser may cache it for a very long time. If you change something in the file you also update the number in the querystring, which will make the browser refetch the file. This works because caching is for unique filenames and the querystring is part of the filename (as far as the browser is concerned).
A similar approach to this is to use rewrite rules in the web server to have some part of the file name which it doesnät care about. Here's a Nginx rule to show what I mean:
rewrite ^/style\..*\.css$ /style.css;
I use this rule to have filenames like style.42750cad6.css, which always points to the file style.css. The text in the middle is changed whenever I change style.css. The difference between the first approach is that this does not use the querystring so the caching will work in more browsers.
ok the way i see it in two ways.
it can be used to load js without caching
for every request to the server, the server might log information(if logging is enabled), if i am using it for analytics i can therefore use a different parameter for locations and from the log i can analyse and get required details.

Making a file readable only by JavaScript and/or Flash

I'm a bit new to web development so forgive the slightly beginner question. Can anyone give me some general pointers on how to prevent downloading of files while displaying content with JavaScript/Flash widgets?
The basic dilemma is making files playable by page widgets while preventing direct downloads of the source media. However, since JavaScript and Flash are browser-side instead of server-side, I'm not sure how I can do this.
Obfuscating the source file name is another option, but I'm not sure what a good way to do this would be. Maybe hiding with an algorithm in the .swf files? Not sure how immune to reverse compilation .swf is though.
Thanks a bunch.
In fact, you can't. There are two types of downloads; normal (direct) one and the one via streaming.
I would advise you to use the direct one but passing an authorization key with it.
An example of such a URL would look like:
/download?file=134&auth=A34C56E4FCD3908DA
^ ^ ^
| | '- The predefined access token
| '- The requested file
'- Gateway script
Don't forget that you must store the sensitive files somewhere outside of your document root.
The gateway script would look like (pseudo-code):
if( validate_token( get('auth') ){
file_id = get('file');
file_name = get_file_name( file_id );
data = file_read_all( file_name );
}
if your intention is to prevent somebody stole your source code, you can't do anything, because javascript NEED to be downloaded by browser. you can translate your critical code to some server-side language and pass to brwoser (or flash) only his output. Or try some server-side javascript engine

Display actual file size next to a hyperlink of a document or download

I've always been required show download size next to the file hyperlink. Only the file in question is rebuilt everyday and the file size can change often. So needless to say the size has been wrong for months. I'm not going to update our site daily to display needless info.
instead of
click here to download (20mb)
I'd prefer
click here to download [sizeof('file.xxx')]
The best solution would be javascript based or similar.
Since the file is on the server the solution would be best using ASP.NET. This blog post shows how to find the size of a file on the server. You may be able to adapt it to your needs.
javascript isn't really the best language to query the file system. There are ways to do it but they are all very hacky and you should stay away from them.
You can get the file size dynamically using server side code though :
long fileSize = (new FileInfo(# ".\file")).Length;
So in your markup, you could have something like :
<asp:Hyperlink runat="server" ID="hyperlinkFile" ...>
In your code behind, set it properly :
this.hyperlinkFile.Text = "Click here to download" + fileSize.ToString();
Use XMLHttpRequest to send a HEAD to the file and parse the HTTP Header that you get back, looking for the Content-Length field.
Something like:
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
if(this.readyState == 2) {
alert(client.getResponseHeader("Content-Length"));
}
}
client.open("HEAD", address);
client.send();
More information here:
http://ajaxpatterns.org/XMLHttpRequest_Call
The final solution will be a mix between server code (asp.net) and client code (js).
You can build a REST service, that based on the file name or path, returns the size.
You can implement a js function that updates the inner text of every with the result of the REST service call.
Do something like this
click here to download (<%= C# or VB code for file size %>)
Inside the <%= %> tag you can put C# or VB code to find the file size. The server will evaluate it and then put the result where that tag is.
Just create a column name 'FileSize' in your database and fill it with asp.net after your upload has finished. This makes sure you won't overload your server too much.
[edit]Sorry didnt see your file size changes every day[/edit]
In that case you could write a little FileSystem Watcher and let it run in the background on your server or you could just get the filesize by checking the FileSystem info, way easier.
I thought about this more...I read all your answers, then clicked on some links to download various files from other websites. The browser tells me the size after I click 'download' in the dialog box.
I'm going to change the mind set that it is even necessary to include in the link.
Our site has so many pointless...('well other sites have this feature')...and the person I replaced didn't realize or care he that those other sites were built with a CMS that does all that automatically. Example: He was hard coding at the bottom of each page 'last updated: 01/01/1900' every time he saved the document.
edit:
I don't like the way I phrased this answer the other day. I realized that it is unnecessary to include the file size in the hyperlink, when all the major browsers will indicate the file size once you click 'download'. Like in my example above, there are so many instances I can find where the developer or webmaster before me added additional work for themselves by including "features" like filesizes/timestamps/etc... In my opinion adding features like that have/are:
No ROI
Likely to always be wrong
Required to have constant maintenance
Cheap way to make your site look "dynamic"
The last thing you do

How do I stop js files being cached in IE?

I've created a page that uses the CKEditor javascript rich edit control.
It's a pretty neat control, especially seeing as it's free, but I'm having serious issues with the way it allows you to add templates.
To add a template you need to modify the templates js file in the CKEditor templates folder. The documentation page describing it is here.
This works fine until I want to update a template or add a new one (or anything else that requires me to modify the js file).
Internet Explorer caches the js file and doesn't pick up the update. Emptying the cache allows the update to be picked up, but this isn't an acceptable solution. Whenever I update a template I do not want to tell all of the users across the organisation to empty their IE cache. There must be a better way!
Is there a way to stop IE caching the js file? Or is there another solution to this problem?
Update
Ok, I found this section in the CKEditor API that will allow me to use the "insert timestamp into the url" solution suggested by several people.
So the script now looks like this:
config.templates_files =
[
'/editor_templates/site_default.js?time=' + utcTimeMilliseconds
];
Thanks for your help guys.
You can add rand seed to your js file. I mean <script src='jsFile.js?seed=12345'
And every time you want to empty cache - change seed number
Update:
as I understood you have to write like this config.templates_files = [ '/mytemplates.js?seed=12345' ];
Youo can add a timestamp query parameter when you include your .js file..
so instead of <script type="text/javascript" src="somefile.js"></script> you can <script type="text/javascript" src="somefile.js?timestampgoeshere"></script>
this should make the file to always get reloaded (the timestamp needs to be dynamic and changing for each load of the page..)
I am afraid you'll have to hack into the FCKEditor code and force the client JavaScript to load fresh copy of the XML file. You can do so by appending a ?random=<a random number> to the URL of the XML file being requested. FCKEditor is opensource so you should be able to locate the lines the request the XML and modify accordingly.
Set Expires-Header accordingly, e.g. in Apache
ExpiresActive On
ExpiresByType text/javascript access
This is not recommended for a real web application, only for intranet scenarios because the files will not be cachable.
every time you load the js file, pass a variable of a random number as a variable.
src='/libs/js/myfile.js?4859487594573
same trick for ajax loaded files.
Multiple methods (don't need to do them all):
press ^F5 (control + F5) - that'll load without cache
set pragma/cache headers on sending
use a random variable in the GET query string
.NET / C# :
public static void DisallowBrowserCache( )
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
}
You could make ASP.NET write a js file to the outputstream (http://server.com/jsFile.aspx, set http headers), and control the caching behavior of the response with the above method.

Categories