簡體   English   中英

將PNG圖片從后端保存到前端到本地Angular Project文件夾

[英]Save PNG image from Backend to Frontend to local Angular Project folder

我想將從后端(Java項目)收到的PNG圖像保存到Angular Project內的文件夾中。 到目前為止,我只能將圖像保存在PC的Downloads /文件夾下,您可以看到文件的下載方式。 我想要的是在項目中靜默下載圖像(當我檢查文件夾以查看存儲的新圖像時)。

后端:

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("getImage")
    public Response getImage() {
        File dir = new File(Utilities.IMAGE_DIRECTORY);
        File[] directoryListing = dir.listFiles();
        String encodedImages = null;

        // Get the first image stored in Backend project folder
        try {
            if (directoryListing != null) {
                // Encode the image in Base64 and save it in a string
                encodedImages = Base64
                                 .getEncoder()
                                 .withoutPadding()
                                 .encodeToString(
                        Files.readAllBytes(directoryListing[0].toPath()));
            }
        } catch (IOException e) {
            e.printStackTrace();
            ...
        }

        // Send the base64 string to Frontend
        return Response
                .status(Response.Status.OK)
                .entity(encodedImages)
                .build();
    }

前端:

  /* Extract Image */
  getImage() {
    this
      .http
      .get(this.baseUrl + "getImage", { responseType: 
       'text' })
      .subscribe((res) => {
        console.log("I received the image: \n" + res);

        // Decode from base64 to PNG
        var decodedImage = atob(res);

        var blob = new Blob([decodedImage], { type: 'image/png' });

        //this method saves the image in Downloads/ and it is not silent
        saveAs(blob, 'imageFileName.png');
    });
  }

既然您的用戶將不需要它自己的圖像,為什么要下載它? 您不需要下載圖像就可以使用它。 僅當您的用戶需要下載圖像時,才可以使用“保存文件”系統。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM