SpringBoot将图片/文件传至前端

1. 返回OutputStream

	@GetMapping("/download")
    public String download (HttpServletResponse response) {
        File file = new File("");
        byte[] bytes = new byte[1024];
        try (OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file)){
            while ((fis.read(bytes)) != -1) {
                os.write(bytes);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

2. 返回base64格式

    @GetMapping("/base64")
    public String getBase64() {
        byte[] data = null;
        String dataStr = null;
        final Response picture = feignServer.getBase64();
        Response.Body body = picture.body();
        try (InputStream is = body.asInputStream()){
            data = is.readAllBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataStr = Base64.encodeBase64String(data);
        return dataStr;
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐