文件下载

文件下载,页面端可以使用<img>标签展示下载的图片

<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>

handleAvatarSuccess (response, file, fileList) {

  this.imageUrl = '/common/download?name=${response.data}'

},

/**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
            //输出流,通过输出流将文件写回浏览器,在浏览器展示图片了
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            //输入流每次读,读完放到bytes数组中,当lens等于-1时读完
            while ((len=fileInputStream.read(bytes))!=-1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

 

posted @ 2023-03-09 19:30  佛系粥米  阅读(137)  评论(0编辑  收藏  举报