0

I have a problem trying to download a file using RestFul. I'm setting the Content-Disposition and the attachment, but when the file is downloaded, it has a random name.

@GET
@Path("{type}/xls")
@Produces("application/vnd.ms-excel")
public Response downloadExcel(@Context HttpHeaders headers...) {
...
File file = getFileToDownload();
Response.ResponseBuilder builder = Response.ok(file);
    String fileName = file.getName();
    builder.header("Content-Disposition", "attachment; filename=" + fileName);
...
return builder.build();

For example, if the file name is "file001.xls", the response is:

Response-Code: 200
Content-Type: application/vnd.ms-excel
Headers: {Content-Disposition=[attachment; filename=file001.xls], Content-Type=[application/vnd.ms-excel], Date=[Tue, 01 Mar 2016 16:18:19 GMT]}

But the downloaded file is named like this: 8fecd36a-a5aa-4b04-b757-4c38ddea11db.xls

Could you help me, please! :-)

amd
  • 1
  • 4
  • What client do you use to download? – JP Moresmau Mar 01 '16 at 16:40
  • I'm using Java (Spring and AngularJS), and the problem occurs in Firefox, Chrome and Safari. Thanks! – amd Mar 01 '16 at 16:50
  • Code samples for example at http://stackoverflow.com/questions/4377589/how-do-i-send-a-file-with-jax-rs have double quotes around the filename... – JP Moresmau Mar 01 '16 at 16:59
  • Thanks but I tried that and it doesn't work... :-( `Headers: {Content-Disposition=[attachment; filename="file001.xls"], Content-Type=[application/vnd.ms-excel], Date=[Tue, 01 Mar 2016 17:12:28 GMT]}` – amd Mar 01 '16 at 17:10
  • a) the way you set the filename may break; see RFC 6266 for the gory details. b) can you post the raw HTTP response you are generating? – Julian Reschke Mar 01 '16 at 17:39
  • Hi! This is de complete response (almost complete...): `Response-Code: 200 Content-Type: application/vnd.ms-excel Headers: {Content-Disposition=[attachment; filename="file001.xls"], Content-Type=[application/vnd.ms-excel], Date=[Thu, 01 Mar 2016 17:12:28 GMT]} PK0�aH_rels/.rels���J1��}�0�n�D�i/E�M�>����a7����}{�u邂�af���$���G�F)�l�ˮ������TGd�B���F����>fU !�D���v�1W)�N�ɣ�2�:��%���[��3`U'g ���SKb`�;��y� � ��(�A��p(�tS6�O:�)?KG���3BQ�4?��k3*$8ɱϳ<�c����r�d����)6V� \2H��#{( z�;��;i�1��!,/...` – amd Mar 03 '16 at 08:24

1 Answers1

0

I've resolved my problem. I've added this header to the response:

builder.header("Access-Control-Expose-Headers", "Content-Disposition");

And retrieve the response at client in that way:

var contentDisposition = response.headers('Content-Disposition');
var initName = contentDisposition.indexOf('filename=') + 9;
var fileName = contentDisposition.substring(initName);

var blob = new Blob([response.data], {type: type});
var blobURL = URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = fileName;
anchor.href = blobURL;
anchor.click();
amd
  • 1
  • 4