Vue3+Springboot图片下载

后端图片下载接口

    @ApiOperation(value = "下载图片")
    @GetMapping("download/{pictureId}")
    public void download(@PathVariable("pictureId") @NotNull(message="参数错误") Long id,
                     HttpServletResponse response) {
        PicturePo picturePo = pictureService.getById(id);
        if(Objects.isNull(picturePo)) BusinessException.throwException(ResultVo.notFound());
        Path path = FolderInitRunner.FOLDER_PATH.resolve(picturePo.getPath());
        if (!Files.exists(path)) {
            log.warn("图片丢失:{}", picturePo.toString());
            BusinessException.throwException(ResultVo.notFound());
        }
        try (OutputStream os = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(picturePo.getTitle() + "." + picturePo.getType(), "UTF-8"));
            response.setContentType("application/octet-stream");
            Files.copy(path, os);
        } catch (Exception e) {
            log.error("图片传输异常:{}",picturePo.toString());
            BusinessException.throwException(ResultVo.error());
        }
    }

前端代码
<template>代码块中加入以下代码

<a :href="link" download="" id="a-download">
    <img :src="link" alt=""/>
</a>

<style>标签中加入以下代码

#a-download{
  display: none;
}

<script>标签中加入以下代码

const link=ref("");
const download=async (id: string) => {
  link.value = axios.defaults.baseURL + '/' + url.download + '/' + id;
  // console.log(document?.getElementById('a-download')?.getAttribute('href'));
  await nextTick();// 等待:href='link'更新完成
  document?.getElementById('a-download')?.click();
}

下载图片时调用download方法,传入图片id,即能下载图片