1. 程式人生 > 程式設計 >以Spring Boot的方式顯示圖片或下載檔案到瀏覽器的示例程式碼

以Spring Boot的方式顯示圖片或下載檔案到瀏覽器的示例程式碼

以Java web的方式顯示圖片到瀏覽器以Java web的方式下載伺服器檔案到瀏覽器

以Spring Boot的方式顯示圖片或下載檔案到瀏覽器
請求例子:http://localhost:8080/image/1564550185144.jpeg

示例程式碼:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.io.IOException;

@Configuration
public class ImageShow implements WebMvcConfigurer {

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
  File directory = new File("image");
  String path = null;
  try {
   path = directory.getCanonicalPath();
  }catch (IOException e){
   e.printStackTrace();
  }
  registry.addResourceHandler("/image/**").addResourceLocations("file:"+path+"/");
 }

}

執行結果:

顯示圖片

在這裡插入圖片描述

下載檔案

在這裡插入圖片描述

補充:springboot 下載圖片並輸出瀏覽器

@GetMapping(value = "v1/returnGroupCode",produces = MediaType.IMAGE_JPEG_VALUE)
  public byte[] returnGroupCode(@RequestParam("seriesUniqueCode") String seriesUniqueCode){
    URL url = null;
            InputStream is = null;
            ByteArrayOutputStream outStream = null;
            HttpURLConnection httpUrl = null;
            try{
              url = new URL(pdGroupcodeSeriesInfo.getQrCodeUrl());
              httpUrl = (HttpURLConnection) url.openConnection();
              httpUrl.connect();
              httpUrl.getInputStream();
              is = httpUrl.getInputStream();
              outStream = new ByteArrayOutputStream();
              //建立一個Buffer字串
              byte[] buffer = new byte[1024];
              //每次讀取的字串長度,如果為-1,代表全部讀取完畢
              int len = 0;
              //使用一個輸入流從buffer裡把資料讀取出來
              while( (len=is.read(buffer)) != -1 ){
                //用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度
                outStream.write(buffer,len);
              }
              byte[] temp = outStream.toByteArray();
              return temp;
  }

到此這篇關於以Spring Boot的方式顯示圖片或下載檔案到瀏覽器的示例程式碼的文章就介紹到這了,更多相關Spring Boot下載檔案到瀏覽器內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!