iliak iliak - 1 month ago 43
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();
raw.setContentType("image/tiff");
raw.getOutputStream().write(bytes);
raw.getOutputStream().flush();
raw.getOutputStream().close();
return raw;
});


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

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

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


When I try to put the response directly into
fr.readAsArrayBuffer(data);
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'});
fr.readAsArrayBuffer(blob);


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

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

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

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

};
xhr.send();