Download excel file in javascript from Rest API response content-disposition outputs [Object, Object]

只愿长相守 提交于 2019-12-22 08:33:49

问题


I want to download a excel file from my angularJs code. Where i made a http post request to Java Rest API and returned the file with header "Content-Disposition" : "attachment; filename=\"new_excel_file.xlsx\""

Java Code

@Post 
@Path("/excel/trekResult")
@Produces("application/vnd.ms-excel")
public Response getResultsReport(@HeaderParam(Constants.ID) Long userId, @QueryParam(Constants.COMPANY_TREK_ID) Integer companyTrekId) {
String CONTENT_DESPOSITION = "Content-Disposition";
String CONTENT_ATTACHEMENT = "attachment; filename=\"new_excel_file.xlsx\"";

//Generates a excel file in local file system
File excelFile = misHelper.writeToFile(workBook, mis, userId, "trek-results");

return Response.ok().entity((Object)excelFile).
    header(CONTENT_DESPOSITION, CONTENT_ATTACHEMENT).build();

}

On Javascript Side

myService.exportResult($scope.companyTrek.id).then(function(result) {
  if(result !== undefined || result !== '') {
    var blob = new Blob([result], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    var objectUrl = URL.createObjectURL(blob);
    saveAs(blob, 'Trek-Results-'+fetchCurrentDate()+ '.xlsx');
  }
}

Used FileSaver.js to save file.

The output file is [Object, Object]

Tested The locally generated file.

Here is a similar question for reference that didn't help me.

receive an excel file as response in javascript from a Rest service


回答1:


I just noticed the Mime types are different on Java server vs Angular client.
This link shows the different MIME types related to spreadsheets.
Try making them consistent and seeing if that fixed it.
There was also this way without mishelper.



来源:https://stackoverflow.com/questions/29739865/download-excel-file-in-javascript-from-rest-api-response-content-disposition-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!