Detect the end of download stream on browser with jquery function - javascript

I have implemented a function in an .NET application to download a large number of files using a stream with an undefined initial length.
I need to capture, on the browser, when the stream ends to show an alert to the user but I have difficulty understanding how to solve or which workaround to use.
This is my function:
private void OutputStreamZipped(Page page)
{
page.Response.ContentType = "application/zip";
page.Response.AddHeader("content-disposition", "attachment" + ";filename=" + "myFileName.zip");
page.Response.AddHeader("Accept-Ranges", "bytes");
page.Response.AddHeader("Expires", "0");
page.Response.AddHeader("Pragma", "cache");
page.Response.AddHeader("Cache-Control", "private");
page.Response.Buffer = false;
page.Response.BufferOutput = false;
byte[] buffer = new byte[2 * 1024 * 1024];
try
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream))
{
zipOutputStream.SetLevel(3);
DirectoryInfo DI = new DirectoryInfo(#"C:\myFolder");
foreach (var i in DI.GetFiles())
{
Stream fs = File.OpenRead(i.FullName);
ZipEntry zipEntry = new ZipEntry(ZipEntry.CleanName(i.Name));
zipEntry.Size = fs.Length;
zipOutputStream.PutNextEntry(zipEntry);
int count = fs.Read(buffer, 0, buffer.Length);
while (count > 0)
{
zipOutputStream.Write(buffer, 0, count);
count = fs.Read(buffer, 0, buffer.Length);
if (!Response.IsClientConnected)
{
break;
}
Response.Flush();
}
fs.Close();
}
zipOutputStream.Close();
}
Response.Flush();
page.Response.SuppressContent = true;
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception)
{
throw;
}
}
Thanks to anyone who can give me a tip

Related

How to send an image from server to client with Web Socket using Java / Javascript?

I'm developing an app that sends an image from server to client with Web Socket, it seems the data was sent, but the image is not showing up in the html page.
I've searched the web for solutions, including Receive Blob in WebSocket and render as image in Canvas and How to send an image from a Java websocket server to use in an HTML5 canvas?
The connection is established properly, and I can even draw a rectangle in the html canvas, but nothing I've tried so far can solve my problem [ send over an image ], my code looks like this :
Server Side :
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;
public class Image_Getter
{
int W,H,g,b;
BufferedImage Buffered_Image = null;
String Image_Path="C:/Dir_WebSocket_Jetty/demo.png";
public Image_Getter(int W,int H)
{
this.W=W;
this.H=H;
Buffered_Image = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
}
BufferedImage getAnImage()
{
try
{
// image = ImageIO.read(new File("image.jpg"));
int x_1=getRandomNumber(0,W/2),x_2=getRandomNumber(W/2,W),r=getRandomNumber(0,230),g=getRandomNumber(60,230),b=getRandomNumber(90,250);
for (int x=0;x<W;x++)
if (x < x_1 || x_2 < x) for (int y=0;y<H;y++) setColor(x,y,getRandomNumber(0,253),getRandomNumber(0,253),getRandomNumber(0,253),getRandomNumber(0,253));
else for (int y=0;y<H;y++) setColor(x,y,r,g,b,253);
ImageIO.write(Buffered_Image,"png",new File(Image_Path));
}
catch (Exception e) { System.out.println("Error : " + e.getMessage()); }
return Buffered_Image;
}
void setColor(int x,int y,int r,int g,int b,int a) // r,g,b,a [ alpha (transparency) ] : 0 .. 255
{
int col = (a << 24) | (r << 16) | (g << 8) | b;
Buffered_Image.setRGB(x,y,col);
}
int getRandomNumber(int min,int max)
{
int range=max-min+1,rand=(int)(Math.random()*range)+min;
return rand;
}
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
}
=============================================================
Session s = sMap.get(key);
if (s.isOpen())
{
BufferedImage image = image_getter.getAnImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image,"jpg",baos);
byte[] byteArray = baos.toByteArray();
// s.getBasicRemote().sendText(); // connection.sendMessage(byteArray, 0, byteArray.length);
String base64String = Base64.encode(byteArray);
s.getBasicRemote().sendText(base64String);
// s.getBasicRemote().sendBinary(Base64.encode(byteArray));
// s.getBasicRemote().sendBinary(ByteBuffer.wrap(byteArray));
}
Client side javascript :
class WebSocketImageClient
{
constructor(protocol, hostname, port, endpoint)
{
this.webSocket = null;
this.protocol = protocol;
this.hostname = hostname;
this.port = port;
this.endpoint = endpoint;
}
getServerUrl() { return this.protocol + "://" + this.hostname + ":" + this.port + this.endpoint; }
present() { return "Image Url = [ <font color=#0022CC>" + this.getServerUrl() + "</font> ]"; }
connect()
{
var canvas = document.getElementById("imageCanvas");
var context = canvas.getContext("2d");
try
{
this.webSocket = new WebSocket(this.getServerUrl());
// this.websocket.binaryType = "arraybuffer";
// Implement WebSocket event handlers!
this.webSocket.onopen = function (event)
{
console.log('onopen :: ' + JSON.stringify(event, null, 4));
};
this.webSocket.onmessage = function (event)
{
var msg = event.data;
console.log('onmessage :: ' + JSON.stringify(msg, null, 4));
// var imageoutput = document.getElementById("imageCanvas");
/*
var image = new Image();
image.src = msg;
// image.data = msg;
image.onload = function() {
context.drawImage(image, 0, 0);
};
*/
if (msg)
{
if (msg instanceof Blob)
{
var blob = msg;
var bytes = new Uint8Array(blob);
var image = context.createImageData(canvas.width, canvas.height);
for (var i = 0; i < bytes.length; i++)
{
image.data[i] = bytes[i];
}
// alert("image = "+image);
context.drawImage(image, 0, 0);
}
}
// context.fillStyle = "#0000DD";
// context.fillRect(160, 60, 36, 36); // This can draw a rectangle
// imageoutput.innerHTML = msg;
};
this.webSocket.onclose = function (event)
{
console.log('onclose :: ' + JSON.stringify(event, null, 4));
};
this.webSocket.onerror = function (event)
{
console.log('onerror :: ' + JSON.stringify(event, null, 4));
};
}
catch (exception)
{
console.error(exception);
}
}
getStatus()
{
return this.webSocket.readyState;
}
send(message)
{
if (this.webSocket.readyState == WebSocket.OPEN)
{
this.webSocket.send(message);
}
else
{
console.error('webSocket is not open. readyState=' + this.webSocket.readyState);
}
}
disconnect()
{
if (this.webSocket.readyState == WebSocket.OPEN)
{
this.webSocket.close();
}
else
{
console.error('webSocket is not open. readyState=' + this.webSocket.readyState);
}
}
}
There is no error message, and it looks like this :
Seems a lot of data was sent over to the browser, I can see from developer tool, which looks like this :
And if I un-comment the lines to draw a rectangle, it looks like this :
The image I generated on the server side looks like this :
So, what do I need to do to make the image show up in the html page ?
In your server code you are sending this as a .jpg, but in your client code, you are just trying to draw it without decoding it. Instead of sending a .jpg, maybe send just the color matrix as you are setting it in JS
Now I got it working, on the server side, the code looks like this :
for (String key : sMap.keySet())
{
Session s = sMap.get(key);
if (s.isOpen())
{
BufferedImage image = image_getter.getAnImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ImageIO.write(image,"jpg",baos);
ImageIO.write(image,"png",baos);
byte[] byteArray = baos.toByteArray();
s.getBasicRemote().sendObject(byteArray); // Works on both Swing & browser client
}
else sMap.remove(key);
}
On the browser client side, javascript looks like this :
this.webSocket.onmessage = function (event)
{
var msg = event.data;
console.log('onmessage :: ' + msg); // [object Blob]
var blobUrl = URL.createObjectURL(new Blob([msg]));
var image = new Image();
image.src = blobUrl;
// alert("blobUrl = "+blobUrl); // blob:http://localhost:8080/cc3751d6-5b49-462d-8a6f-f2221c899abf
image.onload = function() { context.drawImage(image, 0, 0); };
};
On Swing client side, java code looks like this :
#OnWebSocketMessage
public void onMessage(InputStream is)
{
try
{
if (imageLabel!=null)
{
BufferedImage img = ImageIO.read(is);
imageLabel.setIcon(new ImageIcon(img));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

Pass video from camera intent to webView

i am trying to implement a webview that start a video intent, and return the video to a webView.
What i try to do:
1) Java - add webAppInterface that open video capture intent:
mWebView = (WebView) findViewById(R.id.webView);
mWebView.addJavascriptInterface(webAppInterface, "Android");
public class WebAppInterface {
...
public void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT,10);
if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
((AppCompatActivity) mContext).startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
...
2) JavaScript - Call it from the webview:
Android.dispatchTakeVideoIntent()
3) Java - Get the Uri, and send path to my webview
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == Activity.RESULT_OK) {
Uri videoUri = intent.getData();
wView.loadUrl("javascript:test('" + videoUri.getPath() + "')");
}
}
4) JavaScript - Get the path in my webView
window.test = (videoUriPath) => {
...
}
My question is, how to access the video?
And maybe there is a totally different way to go about it?
Accessing the video means I'll suppose playing the video in webView. Have a video element in your HTML (suppose id is 'my-video'), then your javascript will be:
window.test = (videoUriPath) => {
var video = document.getElementById('video');
var source = document.createElement('source');
source.setAttribute('src', videoUriPath);
video.appendChild(source);
video.load();
video.play();
}
ok i found a solution, its a little overkill, but its working...
1) JAVA: convert the video to bytes array
byte[] bytes;
byte[] data = new byte[16384];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(data)) != -1) {
output.write(data, 0, bytesRead);
}
bytes = output.toByteArray();
2) JAVA: send encoded chunks (base64) to the webvView
int startIndex = 0;
int chunkSize= 16384;
while(startIndex < bytes.length){
byte[] newArray = Arrays.copyOfRange(bytes, startIndex, startIndex + chunkSize);
startIndex = startIndex + chunkSize;
encodedString = Base64.encodeToString(newArray, Base64.DEFAULT);
wView.loadUrl("javascript:g_sendFile_f('" + encodedString + "')");
}
wView.loadUrl("javascript:g_sendFile_f('" + "finish" + "')");
3) JAVASCRIPT: receive the encode chunks, combine them, and create blob file
let bytesArrFinal_an = []
window.g_sendFile_f = (msg) =>{
// last call
if(msg === "finish"){
let blob = new Blob(byteArrFinal_an,{type : "video/mp4"})
this.test_videoUrl = URL.createObjectURL(blob);
console.log("finish")
return
}
// add bytes to final array
let bytesArr_an = this.b64toByteArr(msg)
bytesArrFinal_an = bytesArrFinal_an.concat(bytesArr_an);
console.log(msg)
}
If someone have a more elegant solution i will be happy the see it!

I want to print to pdf file in javascript, where outputstream and pdfwriter

I am trying to create a PDF from a server-side controller (report) (ireport) with ajax (and so on), and try to return the data to pdfwriter, servletoutputstream, and httpservletresponse. (I do not know exactly what I'm doing, but I'm doing it this way).
The original purpose was to send a server-side pdf file to the client, find the printer and print without a preview window.
Among them, I wrote 'application / pdf' on the server side and 'datetype: text' on the client side ajax (there is an error if I do not use ajax datatype: text)
If you print the results to the console, they will only be listed as unknown code.
Currently I am trying to put it into an iframe frame.
Question!
1. What should I do to use the text string sent to server -> client as pdf or script code?
(I have already asked you two weeks ago)
2. How do I send a pdf to server -> client? I would like to apply it to the screen by expressing it directly in code instead of downloading it. To print out.
ENG)>
// I used ajax only, because I dont know any other way
$.ajax({
url : "url",
data : JSON.stringify(data),
dataType : "text",
type: "POST",
contentType: 'application/json; charset=utf-8',
async : false,
success: function(result){
// I want to view PDF contents and directly print to PDF.
}
})
public Params createIbExItemLabelReport(HttpServletRequest resq, HttpSession session, Params inParams, HttpServletResponse resp) throws Exception{
Params outParams = ParamsFactory.createParams(inParams);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "0");
List<DataRow> list = new ArrayList<DataRow>();
String reportCd = "15";
String fileName = "ibExItemLabel"+reportCd+"Report";
String nullJpgFile = "";
int flag = 0;
int nullCheck = 0;
for(DataRow dr : inParams.getDataTable("dt_data")){
String imgName = "c:\\WMS\\LABEL\\FIAC021_" +reportCd + ".jpg";
File f = new File(imgName);
if (!f.isFile()) {
flag = 1;
if(nullCheck != 0){
nullJpgFile += ", ";
}
nullJpgFile += "FIAC021";
nullCheck++;
continue;
}
String bacodeCd = "FIAC02120180416001";
dr.setParam("imgName", imgName);
dr.setParam("bacodeCd", bacodeCd);
list.add(dr);
}
if(flag == 1){
outParams.setParam("ERROR_FILE", "제품코드 ["+nullJpgFile+"]의 라벨 사이즈" + reportCd + "인 파일이 존재하지않습니다.");
return outParams;
}
String appPath = session.getServletContext().getRealPath("/");
String pdfPath = null;
List<DataRow> list2 = new ArrayList<DataRow>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).getInt("printQty"); j++){
list2.add(list.get(i));
}
}
Report report = new Report();
pdfPath = report.reportToPdf(session, list2, fileName);
outParams.setParam("fileName", pdfPath);
System.out.println("Found! FileName is ' : "+ pdfPath);
pdfPath = appPath + pdfPath;
pdfPath = pdfPath.replace("//", "/");
ServletOutputStream servletOutput = resp.getOutputStream();
PdfWriter pdfWriter = null;
StringBuffer pdfJs = null;
ByteArrayOutputStream pdfOutput = null;
InputStream pdfInput = null;
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfOutput = convertPDFToByteArrayOutputStream(pdfPath);
int printCopy = 1;
if (printCopy == 0) {
printCopy = 1;
}
if (printCopy > 1) {
PdfCopyFields pdfPrintCopy = new PdfCopyFields(pdfOutput);
for (int i = 0; i < printCopy; i++) {
pdfPrintCopy.addDocument(new PdfReader(outputToInputStream(pdfOutput)));
}
pdfPrintCopy.close();
}
pdfInput = outputToInputStream(pdfOutput);
pdfReader = new PdfReader(pdfInput);
pdfStamper = new PdfStamper(pdfReader, servletOutput);
pdfWriter = pdfStamper.getWriter();
String printerNm = "SINDOH D410 Series PCL";
pdfWriter.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
pdfJs = new StringBuffer();
pdfJs.append("var param=this.getPrintParams();\r");
pdfJs.append("param.printerName=\"").append(printerNm).append("\";\r");
pdfJs.append("param.interactive=param.constants.interactionLevel.silent;\r");
pdfJs.append("param.pageHandling=param.constants.handling.shrink;\r");
pdfJs.append("this.print(param);\r");
pdfJs.append("this.closeDoc();");
pdfWriter.addJavaScript(pdfJs.toString(), false);
servletOutput.flush();
Log.debug("servletOutput " );
if (pdfInput != null) {
try {
pdfInput.close();
} catch (Exception e) {
}
pdfInput = null;
}
if (pdfOutput != null) {
try {
pdfOutput.close();
} catch (Exception e) {
}
pdfOutput = null;
}
if (pdfReader != null) {
pdfReader.close();
pdfReader = null;
}
pdfWriter = null;
try {
if (pdfStamper != null) {
pdfStamper.close();
pdfStamper = null;
}
} catch (Exception e) {
}
resp.setHeader("Content-Disposition", "inline; filename="+pdfPath);
resp.setHeader("Content-Type", "application/pdf; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
Log.debug("before outParams " );
return outParams;
}
private InputStream outputToInputStream(ByteArrayOutputStream source) {
return new ByteArrayInputStream(source.toByteArray());
}
private static ByteArrayOutputStream convertPDFToByteArrayOutputStream(String FilePath) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(new File(FilePath));
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
please answer my question

A console application to get a web page resource, using c# (javascript may cause this)

Aim: To download a website source with using a console application. You can find the used class in the program below.
Question: I use the code below to download a data (source) of a web page. Imagine you use chrome; If you enter first this query string, the web page itself redirects you a view HTML page and you see the data.
Entering this URL, to show the results it redirects itself to second page below. I make it by using javascript.
www.xyz.com/aaa.html?search=aaa&id=1
it redirects here: www.xyz.com/ViewResult.html
In an explorer, It works fine . I see 4 HTML tables inside the page when I use google chrome view source option. Bu in my application I see only two tables of the 4 . The two tables inside the web page is missing.(the missing two tables are the second and third.)
How can I overcome to this problem? I want to get the source of the page as I see in chrome.
Bonus informations: There is no iframe.
The particular Code :
string url = "www.xyz.com/aaa.html?search=aaa&id=1";
WebPage pG = ss.RequestPage(url, "", "GET");
pG = ss.RequestPage("www.xyz.com/ViewResult.html");
string source= pG.Html;
public WebPage RequestPage(Uri url, string content, string method, string contentType)
{
string htmlResult;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = null;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] contentData = encoding.GetBytes(content);
request.Proxy = Proxy;
request.Timeout = 60000;
request.Method = method;
request.AllowAutoRedirect = false; // false
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Referer = LastUrl;
request.KeepAlive = true; //false,
request.UserAgent = UserAgent;
request.Headers.Add("Accept-Language", "en-us,en;q=0.5");
//request.Headers.Add("UA-CPU", "x86");
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
String cookieString = "";
foreach (KeyValuePair<String, String> cookiePair in Cookies)
cookieString += cookiePair.Key + "=" + cookiePair.Value + ";";
if (cookieString.Length > 2)
{
String cookie = cookieString.Substring(0, cookieString.Length - 1);
request.Headers.Add("Cookie", cookie);
}
if (method == "POST")
{
request.ContentLength = contentData.Length;
request.ContentType = contentType;
Stream contentWriter = request.GetRequestStream();
contentWriter.Write(contentData, 0, contentData.Length);
contentWriter.Close();
}
int attempts = 0;
while (true)
{
try
{
response = (HttpWebResponse)request.GetResponse();
if (response == null)
throw new WebException();
break;
}
catch (WebException)
{
if (response != null)
response.Close();
if (attempts == PageReattempts)
{
throw;
}
else { }
// Wait three seconds before trying again
Thread.Sleep(3000);
}
attempts += 1;
}
// Tokenize cookies
if (response.Headers["Set-Cookie"] != null)
{
String headers = response.Headers["Set-Cookie"].Replace("path=/,", ";").Replace("HttpOnly,", "");
foreach (String cookie in headers.Split(';'))
{
if (cookie.Contains("="))
{
String[] splitCookie = cookie.Split('=');
String cookieKey = splitCookie[0].Trim();
String cookieValue = splitCookie[1].Trim();
if (Cookies.ContainsKey(cookieKey))
Cookies[cookieKey] = cookieValue;
else
Cookies.Add(cookieKey, cookieValue);
}
else
{
if (Cookies.ContainsKey(cookie))
Cookies[cookie] = "";
else
Cookies.Add(cookie, "");
}
}
}
htmlResult = ReadResponseStream(response);
response.Close();
if (response.Headers["Location"] != null)
{
response.Close();
Thread.Sleep(1500);
String newLocation = response.Headers["Location"];
WebPage result = RequestPage(newLocation);
return new WebPage(result.Html, new WebPage(htmlResult));
}
LastUrl = url.ToString();
return new WebPage(htmlResult);
}
1-WebBrowser :
public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
{
public ExtendedWebBrowser()
{
// Ensure that ScriptErrorsSuppressed is set to false.
this.ScriptErrorsSuppressed = true;
this.ProgressChanged += ExtendedWebBrowser_ProgressChanged;
}
private void ExtendedWebBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
// InjectAlertBlocker();
string alertBlocker = #"window.alert = function () { };
window.print = function () { };
window.open = function () { };
window.onunload = function () { };
window.onbeforeunload = function () { };";
var webBrowser = sender as WebBrowser;
webBrowser?.Document?.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
this.Document?.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
}
public void NavigationWaitToComplete(string url)
{
bool complete = false;
NavigationAsync(url).ContinueWith((t) => complete = true);
while (!complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
public void NavigationWaitToComplete(string url, string targetFrameName, byte[] postData, string additionalHeaders)
{
bool complete = false;
NavigationAsync(url, targetFrameName, postData, additionalHeaders).ContinueWith((t) => complete = true);
while (!complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
public async Task NavigationAsync(string url, string targetFrameName, byte[] postData, string additionalHeaders)
{
TaskCompletionSource<bool> tcsNavigation = new TaskCompletionSource<bool>(); ;
TaskCompletionSource<bool> tcsDocument = new TaskCompletionSource<bool>(); ;
Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
DocumentCompleted += (s, e) =>
{
if (ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
Navigate(url, targetFrameName, postData, additionalHeaders);
await tcsNavigation.Task;
// navigation completed, but the document may still be loading
await tcsDocument.Task;
// the document has been fully loaded, you can access DOM here
}
public async Task NavigationAsync(string url)
{
TaskCompletionSource<bool> tcsNavigation = new TaskCompletionSource<bool>(); ;
TaskCompletionSource<bool> tcsDocument = new TaskCompletionSource<bool>(); ;
Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
DocumentCompleted += (s, e) =>
{
if (ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
Navigate(url);
await tcsNavigation.Task;
// navigation completed, but the document may still be loading
await tcsDocument.Task;
// the document has been fully loaded, you can access DOM here
}
}
Calling:
var browser = new ExtendedWebBrowser();
browser.NavigationWaitToComplete("www.xyz.com/aaa.html?search=aaa&id=1");
var html = browser.Document.Body.OuterHtml();
2-CefSharp.OffScreen
private async Task<string> RequestPageAsync(string url, string cachePath, double zoomLevel)
{
var tcs = new TaskCompletionSource<string>();
var browserSettings = new BrowserSettings();
//Reduce rendering speed to one frame per second so it's easier to take screen shots
browserSettings.WindowlessFrameRate = 1;
var requestContextSettings = new RequestContextSettings { CachePath = cachePath };
// RequestContext can be shared between browser instances and allows for custom settings
// e.g. CachePath
using (var requestContext = new RequestContext(requestContextSettings))
using (var browser = new ChromiumWebBrowser(url, browserSettings, requestContext))
{
if (zoomLevel > 1)
{
browser.FrameLoadStart += (s, argsi) =>
{
var b = (ChromiumWebBrowser)s;
if (argsi.Frame.IsMain)
{
b.SetZoomLevel(zoomLevel);
}
};
}
browser.FrameLoadEnd += (s, argsi) =>
{
var b = (ChromiumWebBrowser)s;
if (argsi.Frame.IsMain)
{
b.GetSourceAsync().ContinueWith(taskHtml =>
{
tcs.TrySetResult(taskHtml.Result);
});
}
};
}
return tcs.Task.Result;
}
Calling :
RequestPageAsync("www.xyz.com/aaa.html?search=aaa&id=1", "cachePath1", 1.0);

HTML5 read video metadata of mp4

Using HTML5 I am trying to get the attribute (ie rotation), located in the header of a mp4 (I play it using a video tag), to do this I am trying to get the bytes that make up the header, and knowing the structure, find this atom.
Does anyone know how to do this in javascript?
You can use mediainfo.js,
It's a porting of mediainfo (cpp) in javascript compiled with emsciptem.
Here is a working example: https://mediainfo.js.org/
You will need to include the js/mediainfo.js file and put mediainfo.js.mem file in the same folder.
You need to check the sources on this file to see how it works:
https://mediainfo.js.org/js/mediainfopage.js
[...]
function parseFile(file) {
if (processing) {
return;
}
processing = true;
[...]
var fileSize = file.size, offset = 0, state = 0, seekTo = -1, seek = null;
mi.open_buffer_init(fileSize, offset);
var processChunk = function(e) {
var l;
if (e.target.error === null) {
var chunk = new Uint8Array(e.target.result);
l = chunk.length;
state = mi.open_buffer_continue(chunk, l);
var seekTo = -1;
var seekToLow = mi.open_buffer_continue_goto_get_lower();
var seekToHigh = mi.open_buffer_continue_goto_get_upper();
if (seekToLow == -1 && seekToHigh == -1) {
seekTo = -1;
} else if (seekToLow < 0) {
seekTo = seekToLow + 4294967296 + (seekToHigh * 4294967296);
} else {
seekTo = seekToLow + (seekToHigh * 4294967296);
}
if(seekTo === -1){
offset += l;
}else{
offset = seekTo;
mi.open_buffer_init(fileSize, seekTo);
}
chunk = null;
} else {
var msg = 'An error happened reading your file!';
console.err(msg, e.target.error);
processingDone();
alert(msg);
return;
}
// bit 4 set means finalized
if (state&0x08) {
var result = mi.inform();
mi.close();
addResult(file.name, result);
processingDone();
return;
}
seek(l);
};
function processingDone() {
processing = false;
$status.hide();
$cancel.hide();
$dropcontrols.fadeIn();
$fileinput.val('');
}
seek = function(length) {
if (processing) {
var r = new FileReader();
var blob = file.slice(offset, length + offset);
r.onload = processChunk;
r.readAsArrayBuffer(blob);
}
else {
mi.close();
processingDone();
}
};
// start
seek(CHUNK_SIZE);
}
[...]
// init mediainfo
miLib = MediaInfo(function() {
console.debug('MediaInfo ready');
$loader.fadeOut(function() {
$dropcontrols.fadeIn();
window['miLib'] = miLib; // debug
mi = new miLib.MediaInfo();
$fileinput.on('change', function(e) {
var el = $fileinput.get(0);
if (el.files.length > 0) {
parseFile(el.files[0]);
}
});
});
Here is the Github address with the sources of the project: https://github.com/buzz/mediainfo.js
I do not think you can extract such detailed metadata from a video, using HTML5 and its video-tag. The only things you can extract (video length, video tracks, etc.) are listed here:
http://www.w3schools.com/tags/ref_av_dom.asp
Of course, there might be special additional methods available in some browsers, but there is no "general" approach - you would need more than the existing methods of HTML5.

Categories

Resources