Send pdf as byte Array to front end and download a file JAVA (Play framework)

时间:2015-10-29 15:41:35

标签: java pdf playframework binary bytearray

I'm creating pdf on my backend java application. when I save bytearray (my pdf file) on server storage pdf file is ok... I can open it looks good (98kb)

When I send this byte array as response for my request to a browser and save file as pdf on client computer only what I see after openning pdf is blank page. Weight of pdf(client) is bigger 128kB which is wierd.

I assume the problem is somewhere inside my javascript code:

$http
    .post("/myUrl", JSON.stringify({img1: chart1URL,img2: chart2URL, img3: chart3URL,img4: chart4URL,img5: chart5URL,img6: chart6URL, site: $scope.criteria.siteNames[0], ward: $scope.criteria.wardNames[0]}),

        {})
    .success(
        function(data){
            debugger;
            //var blob = new Blob([data], {type: 'application/*'});
            //var objectUrl = URL.createObjectURL(blob);
            //window.open(objectUrl);
            var blob=new Blob([data], {type: 'application/octet-stream'});
            var link=document.createElement('a');
            link.href=window.URL.createObjectURL(blob);
            link.download="testFile.pdf";
            link.click();
        }
    );
};

Why test file is bigger then file on backend?

I attach also backend code:

File file = ("myCorrectFile.pdf");
byte[] bytes = FileUtils.readFileToByteArray(file);
response().setContentType("application/octet-stream");
            response().setHeader("Content-disposition","attachment; filename=test.pdf");
            return ok(bytes);

1 个答案:

答案 0 :(得分:0)

您是否需要发布ajax电话?这也可以通过get方法完成。 整个javascript代码可以替换为

window.open("url?param=" + parameters, "_self")

但是get方法有其自身的缺点,即最大URL长度为2048个字符,取决于你的网址有多大。