简体   繁体   中英

Receiving ByteArrayResource( from java) into Blob (into javascript)

any help to my problem would be really appreciated. Here is the context:

I am currently sending a zip file from java RestControler:

public ResponseEntity<Resource> download(@RequestBody ProjectDTO projectDTO) {
    Project project = ProjectDTO.toProject(projectDTO);
    byte[] out = initApplicationService.download(project);
    ByteArrayResource resource = new ByteArrayResource(out);
    return ResponseEntity
      .ok()
      .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + getZipFilename(project))
      .contentType(MediaType.parseMediaType("application/octet-stream"))
      .contentLength(out.length)
      .header("X-Suggested-Filename", getZipFilename(project))
      .body(resource);
  }

This works really well because i can dowload it through swagger.

But on plain javascript front, i can't figure out what i am missing: primary:

const download = async (): Promise<void> => {
      if (project.value.folder !== '') {
        await projectService
          .download(toProject(project.value))
          .then(response => {
              const url = window.URL.createObjectURL(new Blob([response],{type:'application/octet-stream'}));
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', project.value.baseName + '.zip');
              document.body.appendChild(link);
              link.click();
          })
          .catch(error => logger.error('Downloading project failed', error));
      }
    };

calling secondary:

async download(project: Project): Promise<ArrayBuffer> {
    const restProject: RestProject = toRestProject(project);
    return this.axiosHttp
      .post<ArrayBuffer, RestProject>('api/projects/download', restProject)
      .then(response => new Uint8Array(response.data));
  }

It dowloads well a zip but well opening it i got the following error: "An error occured during archive loading" Thanks to any help:)

I added the responseType in post request and i also removed Uint8Array convertion and it worked fine.

return this.axiosHttp
      .post<ArrayBuffer,RestProject>('api/projects/download', restProject,{ responseType: 'blob' })
      .then(response => response.data);

I guess that when receiving the datas, axios needs to know what is coming to convert correctly it in the proper format. on the fly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM