iliak iliak - 10 months ago 133
Java Question

Reading get response with TIFF file in JavaScript

I am developing a web-application where I try to display TIFF file requested from a server. I use this approach to display a TIFF file, but I need to get an image from a server via a GET request instead of opening the file from a local computer.

On the server side I am using a Spark-Java framework to send a response. This is the Java code for that purpose:

get("tiff", (request, response) -> {
byte[] bytes = Files.readAllBytes(Paths.get("temp/201600004068.tif"));
HttpServletResponse raw = response.raw();
return raw;

I can't figure out how to handle the response (input stream in response) in JavaScript to read the file with

$.get( "/tiff", function( data ) {
var parentEl = $(this).parent();
var fr = new FileReader();
fr.onload = function(e) {
//Using tiff.min.js library -
console.debug("Parsing TIFF image...");
//initialize with 100MB for large files
TOTAL_MEMORY: 100000000
var tiff = new Tiff({
var tiffCanvas = tiff.toCanvas();
"max-width": "1000000px",
"width": "100%",
"height": "auto",
"display": "block",
"padding-top": "10px"

fr.onloadend = function(e) {
console.debug("Load End");
fr.readAsArrayBuffer(data); });

When I try to put the response directly into
I got an error
Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'

When I try to create a Blob based on the response

var blob = new Blob([data], {type: 'image/tiff'});

it's not able to parse TIFF file.

My response looks like this:

Local Host Response

and I don't understand the meaning of that response.

So how do I retrieve the file from this response?

Thanks for any help!

Answer Source

I prefer XMLHttpRequest .Since you are writing bytes you can get the data as arraybuffer in XMLHttpRequest.

var xhr = new XMLHttpRequest();'GET', "assets/tif/sample.tif", true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
    var arrayBuffer = this.response;
        TOTAL_MEMORY: 100000000
    var tiff = new Tiff({
        buffer: arrayBuffer
    var dataUrI = tiff.toDataURL();