以Spring Boot的方式顯示圖片或下載文件到瀏覽器的示例代碼
以Java web的方式顯示圖片到瀏覽器以Java web的方式下載服務(wù)器文件到瀏覽器
以Spring Boot的方式顯示圖片或下載文件到瀏覽器請(qǐng)求例子: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+'/'); }}
運(yùn)行結(jié)果:
顯示圖片
下載文件
補(bǔ)充: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)建一個(gè)Buffer字符串 byte[] buffer = new byte[1024]; //每次讀取的字符串長(zhǎng)度,如果為-1,代表全部讀取完畢 int len = 0; //使用一個(gè)輸入流從buffer里把數(shù)據(jù)讀取出來(lái) while( (len=is.read(buffer)) != -1 ){//用輸出流往buffer里寫入數(shù)據(jù),中間參數(shù)代表從哪個(gè)位置開始讀,len代表讀取的長(zhǎng)度outStream.write(buffer, 0, len); } byte[] temp = outStream.toByteArray(); return temp; }
到此這篇關(guān)于以Spring Boot的方式顯示圖片或下載文件到瀏覽器的示例代碼的文章就介紹到這了,更多相關(guān)Spring Boot下載文件到瀏覽器內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. CSS hack用法案例詳解2. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法3. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析4. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明5. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向6. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)7. PHP設(shè)計(jì)模式中工廠模式深入詳解8. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題9. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法10. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)
