以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;@Configurationpublic 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(); //創(chuàng)建一個Buffer字符串 byte[] buffer = new byte[1024]; //每次讀取的字符串長度,如果為-1,代表全部讀取完畢 int len = 0; //使用一個輸入流從buffer里把數(shù)據(jù)讀取出來 while( (len=is.read(buffer)) != -1 ){//用輸出流往buffer里寫入數(shù)據(jù),中間參數(shù)代表從哪個位置開始讀,len代表讀取的長度outStream.write(buffer, 0, len); } byte[] temp = outStream.toByteArray(); return temp; }
到此這篇關于以Spring Boot的方式顯示圖片或下載文件到瀏覽器的示例代碼的文章就介紹到這了,更多相關Spring Boot下載文件到瀏覽器內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)2. css代碼優(yōu)化的12個技巧3. CSS可以做的幾個令你嘆為觀止的實例分享4. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法5. 利用ajax+php實現(xiàn)商品價格計算6. xml中的空格之完全解說7. Vue的Options用法說明8. axios和ajax的區(qū)別點總結9. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?10. ASP刪除img標簽的style屬性只保留src的正則函數(shù)
