将字节数组从Spring Boot下载到Vue前端 [英] Downloading byte array from Spring Boot to Vue frontend

查看:101
本文介绍了将字节数组从Spring Boot下载到Vue前端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能,我正在尝试从MongoDB数据库中读取一个字符串,该字符串是对图像进行解码的图像,然后将其发送到我的Vue前端进行下载.

I have the following functions, I am trying to read a string from my MongoDB database which is an image decode it and send it to my Vue frontend to be downloaded.

@GetMapping(path = "/signature/{signatureId}", produces = MediaType.IMAGE_PNG_VALUE)
public byte[] downloadSignature(String signatureId) {
        Signature signature = routeRepository.findBySignature(signature);

        byte[] bytes = Base64.getDecoder().decode(signature.getSignature().getBytes(StandardCharsets.UTF_8));


        // This try-catch just saves the signature locally for testing
        // This works successfully so I know there isn't an issue with the byte array
        try {
            Files.write(bytes, new File("signature.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentLength(bytes.length);
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}

在Vue前端上,我有以下内容

On my Vue frontend, I have the following

  async downloadSignature(context, payload) {
    await Route.downloadSignature(context.rootState.User.user, payload)
      .then(({ data }) => {
        const url = window.URL.createObjectURL(
          new Blob([data], { type: "image/png" })
        );
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "signature.png");
        document.body.appendChild(link);
        link.click();
      })
      .catch(() => {
        Message.error("Something went wrong, please try again.");
      });
  }

一切正常,但是下载文件时文件出现问题,我无法成功打开

Everything works successfully but when the file downloads there is an issue with the file and I cannot open it successfully

推荐答案

对于Axios,您需要在请求标头中指定响应类型为blob

With Axios, you need to specify in the request headers that the response type is a blob

像这样

Vue.axios.get(resource, { responseType: "blob" });

关于此的文档很差.

这篇关于将字节数组从Spring Boot下载到Vue前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆