Rectangle 27 16

You're not passing the response data to PDF.js, but an instance of the resource:

var myPdf = myService.$getPdf({ Id: 123 });
myPdf.$promise.then(function() {
    var docInitParams = {
        data: myPdf

You haven't shown your code for $getPdf, but I guess that it is something equivalent to

var myService = $resource('/foo', {}, {$getPdf:{responseType: 'arraybuffer'}});
var myPdf = myService.$getPdf();

By default, an AngularJS $resource treats the response as an object (deserialized from JSON) and copies any properties from the object to the resource instance (myPdf in the previous snippet).

Obviously, since your response is an array buffer (or Blob, typed array or whatever), this is not going to work. One of the ways to get the desired response is to use transformResponse to wrap the response object in an object:

var myService = $resource('/foo', {}, {
    $getPdf: {
        responseType: 'arraybuffer',
        transformResponse: function(data, headersGetter) {
            // Stores the ArrayBuffer object in a property called "data"
            return { data : data };
        }
    }
});
var myPdf = myService.$getPdf();
myPdf.$promise.then(function() {
    var docInitParams = {
        data: myPdf.data
    };

    PDFJS.getDocument(docInitParams).then(function (pdf) {
        // ...
    });
});

Or simply the following (avoided unnecessary local variables):

myService.$getPdf().$promise.then(function(myPdf) {
    PDFJS.getDocument({
        data: myPdf.data
    }).then(function (pdf) {
        // ...
    });
});

Thanks! I thought I needed a PDF.JS expert to chime in, but someone with better Angular knowledge was really the key. I was already using transformResponse but not properly since I was treating the resource as if it was the response. Once you pointed that out, everything else fell into place.

Hello, what do you do with the pdf in the .then to load the document into the viewer.html?

If you want to use this with the standard viewer.html, then use PDFViewerApplication.open(myPdf);.

javascript - PDF.JS: Render PDF using an ArrayBuffer or Blob instead o...

javascript angularjs rest angular-resource pdf.js
Rectangle 27 15

You're not passing the response data to PDF.js, but an instance of the resource:

var myPdf = myService.$getPdf({ Id: 123 });
myPdf.$promise.then(function() {
    var docInitParams = {
        data: myPdf

You haven't shown your code for $getPdf, but I guess that it is something equivalent to

var myService = $resource('/foo', {}, {$getPdf:{responseType: 'arraybuffer'}});
var myPdf = myService.$getPdf();

By default, an AngularJS $resource treats the response as an object (deserialized from JSON) and copies any properties from the object to the resource instance (myPdf in the previous snippet).

Obviously, since your response is an array buffer (or Blob, typed array or whatever), this is not going to work. One of the ways to get the desired response is to use transformResponse to wrap the response object in an object:

var myService = $resource('/foo', {}, {
    $getPdf: {
        responseType: 'arraybuffer',
        transformResponse: function(data, headersGetter) {
            // Stores the ArrayBuffer object in a property called "data"
            return { data : data };
        }
    }
});
var myPdf = myService.$getPdf();
myPdf.$promise.then(function() {
    var docInitParams = {
        data: myPdf.data
    };

    PDFJS.getDocument(docInitParams).then(function (pdf) {
        // ...
    });
});

Or simply the following (avoided unnecessary local variables):

myService.$getPdf().$promise.then(function(myPdf) {
    PDFJS.getDocument({
        data: myPdf.data
    }).then(function (pdf) {
        // ...
    });
});

Thanks! I thought I needed a PDF.JS expert to chime in, but someone with better Angular knowledge was really the key. I was already using transformResponse but not properly since I was treating the resource as if it was the response. Once you pointed that out, everything else fell into place.

Hello, what do you do with the pdf in the .then to load the document into the viewer.html?

If you want to use this with the standard viewer.html, then use PDFViewerApplication.open(myPdf);.

javascript - PDF.JS: Render PDF using an ArrayBuffer or Blob instead o...

javascript angularjs rest angular-resource pdf.js
Rectangle 27 99

First of all, you may want to store text in CLOB/NCLOB columns instead of BLOB, which is designed for binary data (your query would work with a CLOB, by the way).

The following query will let you see the first 32767 characters (at most) of the text inside the blob, provided all the character sets are compatible (original CS of the text stored in the BLOB, CS of the database used for VARCHAR2) :

select utl_raw.cast_to_varchar2(dbms_lob.substr(BLOB_FIELD)) from TABLE_WITH_BLOB where ID = '<row id>';

Unfortunately, I do not control the database schema - I just need to peek into the blob... But thanks anyway.

Thanks Mac, that works fine --- But what is the purpose of that "dbms_lob.substr"? --- Only using "select utl_raw.cast_to_varchar2(BLOB_FIELD) ..." seems to give me the same result...?

Doesn't work for me - I get "ORA-06502: PL/SQL: numeric or value error: raw variable length too long". I can put "2000,1" after BLOB_FIELD to get up to 2000 chars, but nothing beyond that.

if the value is longer than 4000 it will throw errors since that's max value for strings in sql. you need to add substr(BLOB_FIELD, 4000, 1). If yo u need longer field support use PL/SQL (up to 32000 I believe)

How do I get textual contents from BLOB in Oracle SQL - Stack Overflow

sql oracle blob
Rectangle 27 99

First of all, you may want to store text in CLOB/NCLOB columns instead of BLOB, which is designed for binary data (your query would work with a CLOB, by the way).

The following query will let you see the first 32767 characters (at most) of the text inside the blob, provided all the character sets are compatible (original CS of the text stored in the BLOB, CS of the database used for VARCHAR2) :

select utl_raw.cast_to_varchar2(dbms_lob.substr(BLOB_FIELD)) from TABLE_WITH_BLOB where ID = '<row id>';

Unfortunately, I do not control the database schema - I just need to peek into the blob... But thanks anyway.

Thanks Mac, that works fine --- But what is the purpose of that "dbms_lob.substr"? --- Only using "select utl_raw.cast_to_varchar2(BLOB_FIELD) ..." seems to give me the same result...?

Doesn't work for me - I get "ORA-06502: PL/SQL: numeric or value error: raw variable length too long". I can put "2000,1" after BLOB_FIELD to get up to 2000 chars, but nothing beyond that.

if the value is longer than 4000 it will throw errors since that's max value for strings in sql. you need to add substr(BLOB_FIELD, 4000, 1). If yo u need longer field support use PL/SQL (up to 32000 I believe)

How do I get textual contents from BLOB in Oracle SQL - Stack Overflow

sql oracle blob
Rectangle 27 68

function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var byteString = atob(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);

  // create a view into the buffer
  var ia = new Uint8Array(ab);

  // set the bytes of the buffer to the correct values
  for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([ab], {type: mimeString});
  return blob;

}

Note: According to MDN, BlobBuilder now is deprecated. No idea since when though. (I know this is quite an old question and answer, just keeping it a little up-to-date.) Instead the Blob accepts an array of parts as first parameter of its constructor.

You can replace the BlobBuilder than blob. var blob = new Blob([ab], {type: mimeString}); return blob;

The duplicated split seems a bit wasteful, given that this could be a very large string.

What is the role of the variable "ia" - its assigned a value but is never used in forming the blob. Why?

javascript - Blob from DataURL? - Stack Overflow

javascript fileapi
Rectangle 27 4

You're a bit out of luck with this because Node doesn't support the Blob interface and so any data you send or receive in Binary with Node is just Binary. You would have to have something that knew how to interpret a Blob object.

Here's an idea, and let me know if this works. Reading through the documentation for websockets\ws it says it supports sending and receiving ArrayBuffers. Which means you can use TypedArrays.

Here's where it gets nasty. You set a certain fixed n number of bytes at the beginning of every TypedArray to signal the mime type encoded in utf8 or what have you, and the rest of your TypedArray contains your file's bytes.

I would recommend using UInt8Array because utf8 characters are 8 bits long and your text will probably be readable when encoded that way. As for the file bits you'll probably just end up writing those down somewhere and appending an ending to it.

Also note, this method of interpretation works both ways whether from Node or in the Browser.

This solution is really just a form of type casting and you might get some unexpected results. The fixed length of your mime type field is crucial.

Here it is illustrated. Copy, paste, set the image file to whatever you want and then run that. You'll see the mime type I set pop out.

var fs = require('fs');


//https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer
function toUint8Array(buffer) {
  var ab = new ArrayBuffer(buffer.length);
  var array = new Uint8Array(ab);

  for (var i = 0; i < buffer.length; ++i) {
    array[i] = buffer[i];
  }

  return array;
}

//data is a raw Buffer object
fs.readFile('./ducklings.png', function (err, data) {
  var mime = new Buffer('image/png');
  var allBuffed = Buffer.concat([mime, data]);
  var array = toUint8Array(allBuffed);
  var mimeBytes = array.subarray(0,9); //number of characters in mime Buffer
  console.log(String.fromCharCode.apply(null, mimeBytes));
});

Here's how you do it on the client side:

Get buffer, an implementation of Node's Buffer API for browsers. The solution to concatenate Byte buffers will work exactly as before. You can append fields like To: and what not as well. The way you format your headers in order to best serve your clients will be an evolving process I'm sure.

var fr = new FileReader();
fr.addEventListener('loadend', function () {
//Asynchronous action in part 2.
  var message = concatenateBuffers(headerStringAsBuffer, fr.result);
  ws.send(message);
});
fr.readAsArrayBuffer(blob);
function concatenateBuffers(buffA, buffB) {
  var byteLength = buffA.byteLength + buffB.byteLength;
  var resultBuffer = new ArrayBuffer(byteLength);
  //wrap ArrayBuffer in a typedArray/view
  var resultView = new Uint8Array(resultBuffer);
  var viewA = new Uint8Array(resultBuffer);
  var viewB = new Uint8Array(resultBuffer);
  //Copy 8 bit integers AKA Bytes
  resultView.set(viewA);
  resultView.set(viewB, viewA.byteLength);
  return resultView.buffer
}

I'm not going to repeat how to convert the concatenated String bytes back into a string because I've done it in the server example, but for turning the file bytes into a blob of your mime type is fairly simple.

new Blob(buffer.slice(offset, buffer.byteLength), {type: mimetype});

This Gist by robnyman goes into further details on how you would use an image transmitted via XHR, put it into localstorage, and use it in an image tag on your page.

yes this is exactly what i'm trying to explain in this question. the "first solution" would be using a UInt8Array to store that info.... but how? keep in mind that javascript on the clientside needs to endoce and decode the binary data... nodejs just has to passtrough the message.... that way i could send everything in binary.

it would be even better if i the size of the binary info could be variable.like thew id3 or exif...

btw i can convert the arraybuffer to a blob...

@coco, can you convert ArrayBuffer to a Blob on Node or in the Browser? In the Browser makes sense because Blob just takes a bunch of bytes and throws them in a special bucket with some nice methods. It won't be able to infer that those bytes were once a JavaScript Object. If JavaScript were a Typed language you would get an error, but since it's not I reckon you can turn just about anything into a Blob.

Also, the reason I recommended the fixed length mime type field is so that you don't have to send another message signaling the length of that field in the array. You could also use some sort of signal character to specify that the mime type message has ended. <CRLF> a.k.a. new line is a common one.

javascript - nodejs binary websocket mimetype handling - Stack Overflo...

javascript node.js websocket binary blob
Rectangle 27 3

Have you tried simplifying first? Instead of reading the BLOB 100 bytes at a time, try simplifying your code to just read all bytes to a file. This way you can easily rule out data layer issues.

c# - reading BLOB image from MySQL database - Stack Overflow

c# .net mysql blob
Rectangle 27 1

Well, the top data you've shown is binary and as such, just prepending the dataURL stuff wont work. You'll need to either do something different with the binary data or send back actual base64 encoded data instead.

Here's a compound example. It shows:

  • reading of a file on disk
  • creating an altered copy with GD unless it's an svg
  • sending it back to the browser as binary data
  • transforming it into a blob and then a dataURL
  • before finally setting the src attribute of an image with it.
  • base64 encoding it, adding the dataURL stuff and outputtting it.
  • retrieving a off-site or cross-protocol image and drawing on a canvas without tainting it.
<?php
    // usefull for images without CORS header
    if (isset($_GET['filename']) == true)
    {
        $filename = urldecode( $_GET['filename'] );
        $data = file_get_contents($filename);
        $finfo = new finfo(FILEINFO_MIME);
        $mimeType = $finfo->buffer($data);
        Header("Content-Type: $mimeType");                  // use the currently detected mime-type
        echo $data;
        die;
    }

    if (isset($_FILES['upload']) == true)
    {
        $alterResult = true;

        // GD wont load svgs :(
        if (strcmp(trim($_FILES['upload']['type']),"image/svg+xml") == 0)
            $alterResult = false;

        // expecting a form element with the type of 'file' and the name of 'upload' - accepting 1 file max
        $data = file_get_contents( $_FILES['upload']['tmp_name'] );

        // draw copy of image, invert the colours, guassian blur 5 times, draw inverted,bluury image beside unaltered copy
        if ($alterResult == true)
        {
            $mImage = imagecreatefromstring ($data);
            $output = imagecreatetruecolor(imagesx($mImage) * 2, imagesy($mImage));
            imagesavealpha ( $mImage , true);
            imagesavealpha ( $output , true);
            imagecopy($output, $mImage, 0, 0, 0, 0, imagesx($mImage) - 1, imagesy($mImage) - 1);
            imagefilter($mImage,IMG_FILTER_NEGATE);
            imagefilter($mImage,IMG_FILTER_GAUSSIAN_BLUR);
            imagefilter($mImage,IMG_FILTER_GAUSSIAN_BLUR);
            imagefilter($mImage,IMG_FILTER_GAUSSIAN_BLUR);
            imagefilter($mImage,IMG_FILTER_GAUSSIAN_BLUR);
            imagefilter($mImage,IMG_FILTER_GAUSSIAN_BLUR);
            imagecopy($output, $mImage, imagesx($mImage), 0, 0, 0, imagesx($mImage) - 1, imagesy($mImage) - 1);
            Header("Content-Type: image/png");
            imagepng($output);
            imagedestroy($mImage);
            imagedestroy($output);
            die;
        }
        // it's an svg, so just return byte-for-byte what we received
        else
        {
            $finfo = new finfo(FILEINFO_MIME);
            $mimeType = $finfo->buffer($data);
            $mimeType = preg_replace("/text\/plain/", "image/svg+xml", $mimeType);  // svgs are wrongly reported as text files
            Header("Content-Type: $mimeType");                  // use the currently detected mime-type
            echo $data;
            die;
        }
    }
?><!doctype html>
<html>
<head>
<script>
function byId(id){return document.getElementById(id)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load',onDocLoaded);
function onDocLoaded(evt)
{
    byId('fileInput').addEventListener('change', onFileChosen);

    // cross origin test
    var can = newEl('canvas');
    var ctx = can.getContext('2d');
    var srcImg = byId('crossOrigin');
    can.width = srcImg.naturalWidth;
    can.height = srcImg.naturalHeight;
    ctx.drawImage(srcImg, 0,0);
    document.body.appendChild(can);
    console.log( can.toDataURL() );
}
function ajaxGet(url, onLoad, onError)
{
    var ajax = new XMLHttpRequest();
    ajax.onload = function(evt){onLoad(this);}
    ajax.onerror = function(evt){onError(this);}
    ajax.open("GET", url, true);
    ajax.send();
}
function ajaxGetBinary(url, onLoad, onError)
{
    var ajax = new XMLHttpRequest();
    ajax.responseType = 'arraybuffer';
    ajax.onload = function(evt){onLoad(this);}
    ajax.onerror = function(evt){onError(this);}
    ajax.open("GET", url, true);
    ajax.send();
}
function ajaxPostForm(url, formElem, onLoad, onError)
{
    var ajax = new XMLHttpRequest();
    ajax.open("POST", url, true);
    ajax.responseType = 'arraybuffer';
    ajax.onload = function(evt){onLoad(this);}
    ajax.onerror = function(evt){onError(this);}
    ajax.send( new FormData(formElem) );
}

function onFileChosen(evt)
{
    // just clear the images if no file selected
    if (this.files.length < 1)
    {
        byId('beforeImg').src = '';
        byId('afterImg').src = '';
        return;
    }

    var file = this.files[0];       // used to set the mime-type of the file when we get it back
    /*
        ==========Before upload/download==========
    */
    let fileReader = new FileReader();
    fileReader.onload = function(evt){byId('beforeImg').src=this.result;}
    fileReader.readAsDataURL(file); 

    /*
        ==========After upload/download==========
        send the file to the backend (also this source-file), then the back-end will read the temporary file and output it.
        we catch this binary output and make an image element with it
    */
    ajaxPostForm('<?php echo $_SERVER['PHP_SELF']; ?>', byId('mForm'), onPostOkay, function(){});
    function onPostOkay(ajax)
    {
        let arrayBuffer = ajax.response;
        if (arrayBuffer)
        {
            let byteArray = new Uint8Array(arrayBuffer);
            let blob = new Blob([byteArray], {type: file.type });
            byId('afterImg').src = URL.createObjectURL(blob);
        }
    }
}
</script>
<style>
.panel
{
    display: inline-block;
    padding: 8px;
    border-radius: 8px;
    border: solid 1px black;
    text-align: center;
}
</style>
</head>
<body>
    <!-- RESULT of below: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA......." -->
    <img id='crossOrigin' src='base64.php?filename=https%3A%2F%2Fmy.totalwellbeingdiet.com%2Fimg%2Fcsiro%2Flogos%2Fcsiro.png'/>

    <!-- RESULT of below: "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported." -->
    <!-- <img id='crossOrigin' src='https://my.totalwellbeingdiet.com/img/csiro/logos/csiro.png'/> -->

    <form id='mForm' method='post' enctype="multipart/form-data">
        <input id='fileInput' type='file' name='upload'/>
    </form>
    <div class='panel'>
        <img id='beforeImg'/><br>
        <strong>Before upload</strong>
    </div>
    <div class='panel'>
        <img id='afterImg'/><br>
        <strong>After upload/mod/download</strong>
    </div>
</body>
</html>

Thank you for your answer! The problem is that i cant change the backend, i just get that binary and i have to deal with it

No worries mate, you're welcome. Hey - hang on a minute. Is there any reason you can't simply do img.src = "/api/image"; - I mean it returns image data - that's what the browser wants when it tries to read the resource specified as the source, who cares what the url is? Is it possible this is being needlessly complicated?

Amazing! very instructive!

javascript - render an image binary data into a img or canvas tag - St...

javascript html image html5-canvas
Rectangle 27 2

The only way to do it with the Request module is to base a base64 encoded string to the content key. If you don't use this, then you can send data such as a Blob or DOMFile (new File()) instance.

But as we see in the SDK code, the request module sends the data variable on request (if its not a HEAD or GET request).

data
stringify
content

You can use the sdk/io module to read the file as an ArrayBuffer and then turn that ArrayBuffer into a base64 string or binary string.

javascript - Send file via Post using new SDK Firefox Addon - Stack Ov...

javascript firefox firefox-addon firefox-addon-sdk
Rectangle 27 6

After creating the blob:-URL on the background page and passing it to the content script, don't forward it to the web page. Instead, retrieve the blob using XMLHttpRequest, create a new blob:-URL, then send it to the web page.

// assuming that you've got a valid blob:chrome-extension-URL...
var blobchromeextensionurlhere = 'blob:chrome-extension....';
var x = new XMLHttpRequest();
x.open('GET', blobchromeextensionurlhere);
x.responseType = 'blob';
x.onload = function() {
    var url = URL.createObjectURL(x.response);
    // Example: blob:http%3A//example.com/17e9d36c-f5cd-48e6-b6b9-589890de1d23
    // Now pass url to the page, e.g. using postMessage
};
x.send();

If your current setup does not use content scripts, but e.g. the webRequest API to redirect request to the cached result, then another option is to use data-URIs (a File or Blob can be converted to a data-URI using <FileReader>.readAsDataURL. Data-URIs cannot be read using XMLHttpRequest, but this will be possible in future versions of Chrome (http://crbug.com/308768).

Thanks a lot. That's worked like a charm :)

javascript - Pass large blob or file from chrome extension - Stack Ove...

javascript google-chrome google-chrome-extension
Rectangle 27 2

I solved the problem by using a Blob URL / Object-URL instead of a Data URI:

var csv = 'foo,bar,baz'
var blob = new Blob([csv], {type: "text/csv;charset=utf-8"})

chrome.downloads.download({
    'url': URL.createObjectURL(blob),
    'filename': 'file.csv',
})

In Firefox, access checks for APIs such as downloads.download and tabs.create are stricter than in Chrome. At present, it is only possible to download/open pages if the extension is allowed to load the URL. In Firefox, data:-URLs inherit the principal from the caller (i.e. the origin), and out of caution that is blocked. But you could create a feature request if you think that access to data:-URLs is important (technically, Firefox could use a null principal to solve the concerns of leaking privileges). Here is the bug for opening tabs: bugzil.la/1269456

javascript - Save Data URI as file using downloads.download() API - St...

javascript google-chrome-extension download data-uri firefox-webextensions
Rectangle 27 35

If you need to send it over ajax, then there's no need to use a File object, only Blob and FormData objects are needed.

As I sidenote, why don't you just send the base64 string to the server over ajax and convert it to binary server-side, using PHP's base64_decode for example? Anyway, the standard-compliant code from this answer works in Chrome 13 and WebKit nightlies:

function dataURItoBlob(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    //Old Code
    //write the ArrayBuffer to a blob, and you're done
    //var bb = new BlobBuilder();
    //bb.append(ab);
    //return bb.getBlob(mimeString);

    //New Code
    return new Blob([ab], {type: mimeString});


}

Then just append the blob to a new FormData object and post it to your server using ajax:

var blob = dataURItoBlob(someDataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();

fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);

Thanks for your answer, however, I have already made something like that and it works fine. Its a canvas based image resizer, watermarker and uploader. Waiting for a project to use it on

new FormData();

BlobBuilder is now deprecated and does not work anymore in Chrome !

This post uses deprecated elements such as BlobBuilder, see @cuixiping's answer for a working solution.

jquery - How to convert dataURL to file object in javascript? - Stack ...

javascript jquery fileapi
Rectangle 27 5

In addition to the text (string) messages, the WebSocket API allows you to send binary data, which is especially useful to implement binary protocols. Such binary protocols can be standard Internet protocols typically layered on top of TCP, where the payload can be either a Blob or an ArrayBuffer.

// Send a Blob
var blob = new Blob("blob contents");
ws.send(blob);

// Send an ArrayBuffer
var a = new Uint8Array([8,6,7,5,3,0,9]);
ws.send(a.buffer);

Blob objects are particularly useful when combined with the JavaScript File API for sending and receiving files, mostly multimedia files, images, video, and audio.

Also i suggest to see WebRTC (Technology associated with WebSockets) Web Real-Time Communication (WebRTC) is another effort to enhance the communication capabilities of modern web browsers. WebRTC is peer-to-peer technology for the Web. The first applications for WebRTC are real-time voice and video chat. WebRTC is already a compelling new technology for media applications, and there are many available sample applications online that enable you to test this out with video and audio over the Web. Please check this link

javascript - Using websocket to stream in video tag - Stack Overflow

javascript html5 google-chrome websocket video-streaming
Rectangle 27 1

busboy, multer, and other multipart parsing modules require properly formatted multipart/form-data requests. One easy way to send a request like this with axios is to instead pass a FormData instance instead of a raw File or Blob instance as the data argument.

node.js - React-Node File Uploader - Stack Overflow

node.js express reactjs
Rectangle 27 2

If I understand corretly, you want to send an pdf file to a webapplication, right? I think it would be a solution to base64 code the binary data of the pdf on the iphone (that comes from your blob) and then send it via http post to the webapplication.

No, actually, I have something stored in web application's datastore as blob. I create a http post request from iPhone everything is perfect. But i dont know how to return pdf data to iphone.

ah ok. sorry. My guess would be quite similar though: get the blob out of the database, do a base64 encode on that and write the resulting string to the response . on the iphone side, base64 decode what you get - and you should have your pdf.

Communication Of iPhone and Google App Engine - Stack Overflow

iphone google-app-engine
Rectangle 27 2

The only thing I would add to Josh's answer is that if you don't need to query individual frames or sensors, just store the arrays as BLOBs in the dog_measurement_data table. I have done this before with large binary set of sensor data and it worked out well. You basically query the 2d and 3d arrays with each measurement and manipulate them in code instead of the database.

This should have been posted as a comment to my answer, but, I guess you can't post comments yet :-) In response, I'd say that the downside to this is, you need a format you can reliably store/retrieve from BLOB, like JSON or some other serialized python value. This might not be as easy as it sounds!

python - How to insert arrays into a database? - Stack Overflow

python database-design numpy
Rectangle 27 2

The only thing I would add to Josh's answer is that if you don't need to query individual frames or sensors, just store the arrays as BLOBs in the dog_measurement_data table. I have done this before with large binary set of sensor data and it worked out well. You basically query the 2d and 3d arrays with each measurement and manipulate them in code instead of the database.

This should have been posted as a comment to my answer, but, I guess you can't post comments yet :-) In response, I'd say that the downside to this is, you need a format you can reliably store/retrieve from BLOB, like JSON or some other serialized python value. This might not be as easy as it sounds!

python - How to insert arrays into a database? - Stack Overflow

python database-design numpy
Rectangle 27 1

This isn't going to work. Leave the blob there in the server side. JavaScript on the client side can't do anything sensible with binary data. All it needs is an URL of the image so that it can reference it in the src attribute of a HTML <img> element, so that the webbrowser can in turn do its job of downloading and displaying the image. Best would be to include the image identifier in the URL. The name is unique for the image, right? Use that in the URL instead.

The first step is to let JS create a HTML <img> element with the proper src attribute which points to an URL which returns the image. Assuming that you're preparing the data like follows

String name = "foo.png";
String imageURL = "imageservlet/" + name;
request.setAttribute("imageURL", imageURL);

and are printing it in JSP(!) as if it are JS variables as follows

<script>
    var imageURL = '${imageURL}';
    // ...
</script>

so that they end up in the generated HTML source like follows (rightclick page in browser and do View Source to verify it)

<script>
    var imageURL = 'imageservlet/foo.png';
    // ...
</script>

then you can create the image as follows

var img = document.createElement("img"); // or getElementById("someId")?
img.src = imageURL;
// ... add to document?
<img src="imageservlet/foo.png" />

Now, the second step is to create a servlet which listens on an URL pattern of /imageservlet/*, retrieves the image as an InputStream from the database by the passed-in indentifier and writes it to the OutputStream of the response along a set of correct response headers. Long story short, I've posted several answers before as to how to do it, they contains kickoff code snippets:

i wanted to insert just the link to the image instead of the whole image as a blob but thats the way my mentor wants it...i was thinking of doing ajax calls but havent really figure the whole thing out yet tho...

Sorry, but either your mentor is a complete idiot, or you misunderstood him. You could base64-encode it and then use the data URI scheme, but that isn't going to work across all webbrowsers and definitely not the normal way of serving images.

im looking over the companies codes they seem to do it a similar way.. insert image as blob to table then retrieve it when needed.. i just havent figure out how its all done

I think you should ask your mentor to explain this to you more in detail, possibly run you through some quick examples of his/her thinking (and also a quick run-through of the existing code you talk about). Or have someone more experienced do it with you. If he/she can't do that, he/she is not a mentor. He/she is a "boss" (and a terribly bad one, at that).

java - How I do get an image blob from JSP to JavaScript? - Stack Over...

java javascript database image jsp
Rectangle 27 1

function dataURItoBlob(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var dw = new DataView(ab);
    for(var i = 0; i < byteString.length; i++) {
        dw.setUint8(i, byteString.charCodeAt(i));
    }
    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab], {type: mimeString});
}

module.exports = dataURItoBlob;

jquery - How to convert dataURL to file object in javascript? - Stack ...

javascript jquery fileapi
Rectangle 27 2

var file = document.getElementById('imageUpload');
var mime = "image/jpeg";
var max_width = 100;
var max_height = 100;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();

img.onload = function () {

    // Clear canvas, and resize image
    ctx.clearRect(0, 0, max_width, max_height);
    ctx.drawImage(img,
        0, 0, img.width, img.height, // size of image
        0, 0, max_width, max_height // size of canvas
    );

    // Get image from canvas as a dataURI, and convert to a blob object
    var dataURI = canvas.toDataUrl(mime);
    // Note: This function can be replaced with canvas.toBlob(),
    // once supported by browsers.
    // ---
    var image_blob = (function () {

        var binary = atob(dataURI.split(',')[1]);
        var array = [];
        for(var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {type: mime});

    })();
    // ---

    // Attach blob-object (contains our image) to form object
    var form = new Form();
    form.append("image", image_blob);

    // Send AJAX request with multi-part data
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/route', true);
    xhr.send(form);

    // jQuery version
    //$.ajax({
    //    type: "POST",
    //    url: "/route",
    //    data: form,
    //    processData: false,
    //    contentType: false
    //})
    //.done(function (response) {
    //    console.log(response);
    //});

};
img.src = URL.createObjectURL(file);

javascript - Resize image before upload - convert canvas to a File obj...

javascript html5 file-upload html5-canvas