how to Preview the video file that user wants to upload on the website (PHP, FiileAPI JS) - wordpress

I mean, when a user chooses the video file from their system, have the web-page already show them the files they want to upload.
I'm already using image file to preview using FileAPI JS. The same I want to do with FileAPI JS for video file.
(So, It must be work within my client side)
Thanks & answers are appreciated :)

You can either use FileReader or createObjectURL. They'll both get the job done, but FileReader has slightly broader support in browsers.
createObjectURL will run synchronously and return a Blob URL, a short string referencing the file in memory. and you can free it up immediately after you're done using it.
FileReader will run asynchronously, requiring a callback, providing a Data URI, a much longer string representing the whole file. This can be very big and will be freed from memory in Javascript garbage collection.
Here's an example that first tries createObjectURL and falls back to FileReader. (Please provide your own error checking, etc.)
var video = document.getElementById('video'),
input = document.getElementById('input');
input.addEventListener('change', function (evt) {
var reader = new window.FileReader(),
file = evt.target.files[0],
url;
reader = window.URL || window.webKitURL;
if (reader && reader.createObjectURL) {
url = reader.createObjectURL(file);
video.src = url;
reader.revokeObjectURL(url); //free up memory
return;
}
if (!window.FileReader) {
console.log('Sorry, not so much');
return;
}
reader = new window.FileReader();
reader.onload = function(evt) {
video.src = evt.target.result;
};
reader.readAsDataURL(file);
}, false);
Working example here: http://jsbin.com/isodes/1/edit
Mozilla has a more detailed article with instructions on how to upload once you've got your file.
IE10 supports both, but IE9 supports neither, so you'll have to fall back to a regular form upload without a preview.

Related

Azure blob file download link

I have a blob which I've stored in Azure blob storage (using the development emulator).
Its all saved and I can see it in the server explorer in the blob store (file.mp3 if that matters).
I'm then linking to it in my site but when I click the link I'm getting a 206 (partial content) back (and obviously no file). If I right click save as everything is happy and the file downloads.
I'm sure this is something pretty noobish that I'm missing but I cant see it.
That is because, browser does not download media file as whole, browser requests Range for which Blob Storage correctly responds with one byte and with headers. This is called HTTP streaming, where parts of file will be downloaded in ranges and will be played progressively. In this form of streaming you can skip parts of file and go to end to play the end part of media without downloading whole file.
Imagine you are watching a big movie, and that movie is of 100 MB. And you want to watch last One minute of it, you can move player's tracker forward on timeline and browser will only download last few megabytes as per the timeline structure in Media file. Usually MP4 & similar media containers support file byte position tracking.
Browsers & most media players try to stream the media file if possible.
You can try following download attribute,
Reference: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
download me
You can try following code, from this answer, Reference: Chrome extension: How to save a file on disk
var url = window.webkitURL || window.URL || window.mozURL || window.msURL;
var a = document.createElement('a');
a.download = 'MyHangouts-MomentCapture.jpg';
a.href = url.createObjectURL(dataURIToBlob(data.active, 'jpg'));
a.textContent = 'Click here to download!';
a.dataset.downloadurl = ['jpg', a.download, a.href].join(':');
/**
* Converts the Data Image URI to a Blob.
*
* #param {string} dataURI base64 data image URI.
* #param {string} mimetype the image mimetype.
*/
var dataURIToBlob = function(dataURI, mimetype) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
var bb = new this.BlobBuilder();
bb.append(uInt8Array.buffer);
return bb.getBlob(mimetype);
};

ASP.NET Inconsistent PDF file download results

I'm working on a ASP.NET (3.5) website that contains a treeview; the nodes' values are set to a filepath (on the server) of a PDF file. When the user clicks a treenode, the server-side code gets the node value (file path), creates a FileInfo object, and (after setting all the header Content-type, Cache-Control, etc. correctly) calls Response.TransmitFile(xxxxpath) to send to the user's browser.
This works fine on the major browsers, on major devices (PCs, Macs, iOS devices). The file downloads correctly and opens on the user's machine. But on certain devices and certain browsers, the PDF file does not open. On Android devices, it appears that Firefox downloads and opens the PDFs correctly, but the stock Android browser does not. On a Kindle Fire, it appears the Silk browser downloads the file successfully, but when trying to open it, I see an error: "PDF trailer not found"....or it says the PDF is DRM-protected (which it is not). I haven't tried another browser (if there is one) on the Fire.
I've experimented using anchor links in static HTML markup, and the problem browsers appear to download and display the PDFs correctly when accessed this way. There seems to be an issue (inconsistency?) with the way ASP.NET sends the response to the browser when done via code. I've used Response.Flush, Response.WriteFile, Response.BinaryWrite, Response.Close, Response.End, etc., and they all produce the same result: MOST browsers handle the file, but SOME cannot handle the PDF.
So, is there some issue with the way ASP.NET constructs the Response object (especially when sending back PDFs) that some browsers don't like? TIA.
Quite simply, the answer to your question is "No." You may want to post your code if you have doubts about whether or not you're doing it correctly; otherwise: 'no'. :)
I would think the browsers you mentioned are much more suspect than something as simple and established as writing to the Response stream.
For reference here is a tried and true way I do it using iHttpHandler:
public void ProcessRequest(System.Web.HttpContext context)
{
string sFilePath = context.Server.MapPath(String.Concat("~/App_LocalResources", context.Request.QueryString["path"]));
try
{
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";
int iReadLength = 16384;
int iLastReadLength = iReadLength;
byte[] buffer = new byte[iReadLength];
if (System.IO.File.Exists(sFilePath))
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(sFilePath);
context.Response.AddHeader("Content-Length", fInfo.Length.ToString());
context.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", fInfo.Name));
using (System.IO.FileStream input = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
try
{
while (iLastReadLength > 0 && context.Response.IsClientConnected)
{
iLastReadLength = input.Read(buffer, 0, iLastReadLength);
if (iLastReadLength > 0)
{
context.Response.OutputStream.Write(buffer, 0, iLastReadLength);
context.Response.OutputStream.Flush();
}
}
context.Response.Flush();
}
catch
{
}
finally
{
input.Close();
}
}
}
}
catch
{
}
finally
{
}
}
Since you've indicated you are pulling the file from another place, here is how to write that to a memory stream. Just pull from your Response Stream from the remote server (or File Stream, Sql Binary Reader, w/e really), then reset your MemoryStream position and then use the functionality above to write to your Response stream to the client.
int iReadLength = 16384;
long lLastReadLength = iReadLength;
long lDataIndex = 0;
byte[] buffer = new byte[iReadLength];
using (System.IO.MemoryStream msTemp = new System.IO.MemoryStream())
{
while (lLastReadLength > 0)
{
lLastReadLength = reader.GetBytes(0, lDataIndex, buffer, 0, iReadLength);
lDataIndex += lLastReadLength;
if (lLastReadLength > 0)
{
msTemp.Write(buffer, 0, Convert.ToInt32(lLastReadLength));
msTemp.Flush();
}
}
// Reset Memory Position
msTemp.Position = 0;
// Now write to the Response Stream here
}

How do I read in FILE contents in QML?

I just need something similar to Fstream to read file IO in QML. Why is there no file IO?
If your file is plain text you can use XMLHttpRequest. For example:
var xhr = new XMLHttpRequest;
xhr.open("GET", "mydir/myfile.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var response = xhr.responseText;
// use file contents as required
}
};
xhr.send();
I know this is old question but you might be still interested in answer.
Here it is: Reading a line from a .txt or .csv file in qml (Qt Quick)
In short, you have here explained how to read files in QML: http://www.developer.nokia.com/Community/Wiki/Reading_and_writing_files_in_QML
All you need is to extend QML with C++.
QML has no built-in file I/O. But - judging from the tone of your post - you already knew that.
How do I read in FILE contents in QML?
You can extend QML's functionalities using C++.
The Getting Started Programming with QML tutorial from the Qt Reference Documentation shows you how to build a text editor. This includes file I/O using C++.
Why is there no file I/O?
Because QML is based on JavaScript, and JavaScript has no built-in file I/O either.
QML is designed as an (easy) way to build a user interface. You need an actual program to do the rest.
There is built-in file I/O available for QML with the Felgo SDK (formerly V-Play) FileUtils. It works cross-platform on desktop, iOS and Android. More info and examples are also in the latest blog post.
It looks like this:
var documentsData = fileUtils.readFile("subfolder/file.json")
function readConfigFile() {
var xhr = new XMLHttpRequest;
var configaddress = "File:///" + root + "/webconfig.txt" //root = "c:/folder/file.ini";
console.log(configaddress);
xhr.open("GET", configaddress);
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var response = xhr.responseText;
var js = JSON.parse(response)
if (js.address != "") {
service_address = js.address
}
// use file contents as required
}
};
xhr.send();
}
What do you want to read the file for?... if its simple data.. then you are probably better off using QML Offline storage API. Look for that section here.
If you want to deploy a db with your application read this conversation.
If you really want to read the file still, learn C++ and expose your code to QML. That, then, is beyond the scope of my answer.

Downloading data posted to server as a file from Flex

This should be trivial, and I'm pretty sure I did it once before.
I'm trying to post data up to a server and have it bounced back to me as a file download, prompting the native browser file download box. I know the server part works just fine becasue I can post from a demo web form, but when I run the following Flex 3 code, I can't even get the request to fire.
var fileRef:FileReference = new FileReference();
private function saveXmlAsFile(event:MouseEvent):void
{
var fileRequest:URLRequest = new URLRequest();
fileRequest.method = URLRequestMethod.POST;
fileRequest.url = "http://foo.com/dataBounce";
var urlVariables:URLVariables = new URLVariables();
urlVariables.content = "Test content to return" ;
// fileRequest.contentType = "application/x-www-form-urlencoded ";
urlVariables.fileName = "test.xml";
fileRef.addEventListener(SecurityEvent.ALL, onSecurityError);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError2);
fileRef.addEventListener(IOErrorEvent.NETWORK_ERROR, onNetworkError);
fileRef.addEventListener(Event.COMPLETE, onComplete);
try
{
fileRef.download(fileRequest, "test.xml");
}catch(error:Error) {
model.logger.error("unable to download file");
}
}
Note, when the call to fileRef.download is called, I can't see any request being made across the network using the traditional Firebug or HTTPWatch browser tools.
EDIT: I should add that this is for < Flash Player 10, so I can't use the newer direct save as file functionality.
Any suggestions? Thanks.
You need to add fileRef.upload to trigger the upload.
Also I would move the download statement to the onComplete so the file isn't requested before it's been uploaded.
Your explanation is pretty clear, but when I look at your code, I'm feel like I'm missing something.
The code looks like you're trying to do half of the upload part and half of the download part.
I think the code you currently have posted would work to trigger a download if you set the .method value to GET. I believe you will also need to include the filename as part of the .url property.
However, to post something and then trigger a download of it, you need two separate operations - the operation to post the data and then an operation to download it, which should probably be called from the upload operation's onComplete handler.
OK, I believe I figured out one of the things that's going on.
When you don't set the URLRequest.data property, it defaults the request method to "GET".
So, the working code looks like, with the data set to the posted URL variables:
private var fileRef:FileReference;
private function saveRawHierarchy(event:MouseEvent):void
{
var fileRequest:URLRequest = new URLRequest();
fileRequest.method = URLRequestMethod.POST;
fileRequest.url = "http://foo/bounceback";
var urlVariables:URLVariables = new URLVariables();
urlVariables.content = "CONTENT HERE";
urlVariables.fileName = "newFileName.xml";
fileRequest.data = urlVariables;
fileRef = new FileReference();
fileRef.addEventListener(Event.COMPLETE, onComplete);
try
{
fileRef.download(fileRequest, "appHierarchies.xml");
}catch(error:Error) {
model.logger.error("unable to download file");
}
}
Not sure what was wrong about the request not being made before, though.

Flex 3 - how to support HTTP Authentication URLRequest?

I have a Flex file upload script that uses URLRequest to upload files to a server. I want to add support for http authentication (password protected directories on the server), but I don't know how to implement this - I assume I need to extend the class somehow, but on how to I'm a little lost.
I tried to modify the following (replacing HTTPService with URLRequest), but that didn't work.
private function authAndSend(service:HTTPService):void{
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode("someusername:somepassword");
service.headers = {Authorization:"Basic " + encoder.toString()};
service.send();
}
I should point out that I'm not knowledgeable when it comes to ActionScript / Flex, although I have managed to successfully modify the upload script somewhat.
[Edit] - here is an update of my progress, based on the answer below, although I still cannot get this to work:
Thank you for your assistance. I've tried to implement your code but I've not had any luck.
The general behaviour I'm experiencing when dealing with HTTP authenticated locations is that with IE7 all is well but in Firefox when I attempt to upload a file to the server it displays an HTTP authentication prompt - which even if given the correct details, simply stalls the upload process.
I believe the reason IE7 is ok is down to the the session / authentication information being shared by the browser and the Flash component - however, in Firefox this is not the case and I experience the above behaviour.
Here is my updated upload function, incorporating your changes:
private function pergress():void
{
if (fileCollection.length == 0)
{
var urlString:String = "upload_process.php?folder="+folderId+"&type="+uploadType+"&feid="+formElementId+"&filetotal="+fileTotal;
if (ExternalInterface.available)
{
ExternalInterface.call("uploadComplete", urlString);
}
}
if (fileCollection.length > 0)
{
fileTotal++;
var urlRequest:URLRequest = new URLRequest("upload_file.php?folder="+folderId+"&type="+uploadType+"&feid="+formElementId+"&obfuscate="+obfuscateHash+"&sessidpass="+sessionPass);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = new URLVariables("name=Bryn+Jones");
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode("testuser:testpass");
var credsHeader:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + encoder.toString());
urlRequest.requestHeaders.push(credsHeader);
file = FileReference(fileCollection.getItemAt(0));
file.addEventListener(Event.COMPLETE, completeHandler);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
file.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
file.upload(urlRequest);
}
}
As stated above, I seem to be experiencing the same results with or without the amendments to my function.
Can I ask also where the crossdomain.xml should be located - as I do not currently have one and am unsure where to place it.
The syntax is a little different for URLRequest, but the idea's the same:
private function doWork():void
{
var req:URLRequest = new URLRequest("http://yoursite.com/yourservice.ext");
req.method = URLRequestMethod.POST;
req.data = new URLVariables("name=John+Doe");
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode("yourusername:yourpassword");
var credsHeader:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + encoder.toString());
req.requestHeaders.push(credsHeader);
var loader:URLLoader = new URLLoader();
loader.load(req);
}
A couple of things to keep in mind:
Best I can tell, for some reason, this only works where request method is POST; the headers don't get set with GET requests.
Interestingly, it also fails unless at least one URLVariables name-value pair gets packaged with the request, as indicated above. That's why many of the examples you see out there (including mine) attach "name=John+Doe" -- it's just a placeholder for some data that URLRequest seems to require when setting any custom HTTP headers. Without it, even a properly authenticated POST request will also fail.
Apparently, Flash player version 9.0.115.0 completely blocks all Authorization headers (more information on this one here), so you'll probably want to keep that in mind, too.
You'll almost surely have to modify your crossdomain.xml file to accommodate the header(s) you're going to be sending. In my case, I'm using this, which is a rather wide-open policy file in that it accepts from any domain, so in your case, you might want to limit things a bit more, depending on how security-conscious you are.
crossdomain.xml:
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*" />
<allow-http-request-headers-from domain="*" headers="Authorization" />
</cross-domain-policy>
... and that seems to work; more information on this one is available from Adobe here).
The code above was tested with Flash player 10 (with debug & release SWFs), so it should work for you, but I wanted to update my original post to include all this extra info in case you run into any issues, as the chances seem (sadly) likely that you will.
Hope it helps! Good luck. I'll keep an eye out for comments.
The FileReference.upload() and FileReference.download() methods do not support the URLRequest.requestHeaders parameter.
http://livedocs.adobe.com/flex/2/langref/flash/net/URLRequest.html
If you want to upload a file, you just need to send the correct headers and the content of file using URLRequest via UploadPostHelper class. This works 100%, i am using this class to upload generated images and CSV files, but you could upload any kind of file.
This class simply prepares the request with headers and content as if you would be uploading the file from a html form.
http://code.google.com/p/as3asclublib/source/browse/trunk/net/UploadPostHelper.as?r=118
_urlRequest = new URLRequest(url);
_urlRequest.data = "LoG";
_urlRequest.method = URLRequestMethod.POST;
_urlRequest.requestHeaders.push(new URLRequestHeader("X-HTTP-Code-Override", "true"));
_urlRequest.requestHeaders.push(new URLRequestHeader("pragma", "no-cache"));
initCredentials();
_loader.dataFormat = URLLoaderDataFormat.BINARY;
//this creates a security problem, putting the content type in the headers bypasses this problem
//_urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
_urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
_urlRequest.requestHeaders.push(new URLRequestHeader('Content-Type', 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary()));
_urlRequest.data = UploadPostHelper.getPostData("file.csv", param[1]);
_loader.load(_urlRequest);
I'm not sure about this but have you tried adding username:password# to the beginning of your url?
"http://username:password#yoursite.com/yourservice.ext"
var service : HTTPService = new HTTPService ();
var encoder:Base64Encoder = new Base64Encoder();
encoder.insertNewLines = false;
encoder.encode("user:password");
service.headers = {Authorization:"Basic " + encoder.toString()};
service.method = HTTPRequestMessage.POST_METHOD;
service.request = new URLVariables("name=John+Doe");
service.addEventListener(FaultEvent.FAULT,error_handler );
service.addEventListener(ResultEvent.RESULT,result_handler);
service.url = 'http://blah.blah.xml?'+UIDUtil.createUID();
service.send();
Seemingly similar problem was solved here. I urge you to also check the Flexcoders post linked to in the first post.
The problem was that FireFox uses a separate browser window instance to send the file upload request. The solution is to manually attach the session id to the request url. The session id is not attached as a regular GET variable, but with a semicolon (the reason for this syntax is unknown to me).
Flash is very limited in terms of what sort of headers you can pass with an http request (and it changes between browsers and OSes). If you get this to work on one browser/OS, make sure you test it on the others.
The best thing to do is not mess with HTTP headers.
We have the same issue (uploading to Picasa Web Albums from flash) and post through a proxy on our server. We pass the extra headers through as post parameters and our proxy does the right thing.
"http://username:password#yoursite.com/yourservice.ext"
This doesn't work in IE (http://www.theregister.co.uk/2004/01/30/ms_drop_authentication_technique/) and doesn't seem to work in Chrome either.
probably not usable in Flash
Here is a work-around when using ASP.Net based in part on the work here.
I built a component that dynamically writes Flex objects to the page so they can be used in UpdatePanels. Message me if you want they code. To solve the above problem in pages where authentication cookies will need to be sent by URLRequest, I add the values in as flashVars.
This code only works in my object, but you get the idea
Dictionary<string, string> flashVars = new Dictionary<string, string>();
flashVars.Add("auth", Request.Cookies["LOOKINGGLASSFORMSAUTH"].Value);
flashVars.Add("sess", Request.Cookies["ASP.NET_SessionId"].Value);
myFlexObject.SetFlashVars(flashVars);
Then in the Flex Object, check for the params
if (Application.application.parameters.sess != null)
sendVars.sess= Application.application.parameters.sess;
if (Application.application.parameters.auth != null)
sendVars.au= Application.application.parameters.auth;
request.data = sendVars;
request.url = url;
request.method = URLRequestMethod.POST;
Finally stuff the cookies in on global.asax BeginRequest
if (Request.RequestType=="POST" && Request.Path.EndsWith("upload.aspx"))
{
try
{
string session_param_name = "sess";
string session_cookie_name = "ASP.NET_SESSIONID";
string session_value = Request.Form[session_param_name]; // ?? Request.QueryString[session_param_name];
if (session_value != null) { UpdateCookie(session_cookie_name, session_value); }
}
catch (Exception) { }
try
{
string auth_param_name = "au";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
string auth_value = Request.Form[auth_param_name];// ?? Request.QueryString[auth_param_name];
if (auth_value != null) { UpdateCookie(auth_cookie_name, auth_value); }
}
catch (Exception) { }
}
Hope this help someone avoid the 6 hours I just spent addressing this. Adobe has closed the issue as unresolvable, so this was my last resort.

Resources