1. 程式人生 > >java web 訪問本地的靜態資源(圖片)

java web 訪問本地的靜態資源(圖片)

背景: 使用者上傳一張圖片到伺服器,通過瀏覽器顯示這張圖片

實現:

第一步:<a href="/test/showImageServlet?filename=測試的圖片一枚.jpg">預覽圖片</a> 

第二步:servlet 實現:

-------------------------------------------------------------------------------------------------------------------------------------------------------

//通過瀏覽器顯示訪問圖片的url,直接顯示出來
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
response.setContentType("text/html; charset=UTF-8");//設定返回資料的格式
response.setContentType("image/jpeg");
//獲取圖片的url
String fileName = request.getParameter("filename");
//處理圖片url的編碼格式
String newpath = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
String absolutePath = rootPath + newpath;
//檔案流
FileInputStream fis = new FileInputStream(absolutePath);
//輸出流
OutputStream os = response.getOutputStream();
try{
int count = 0;
byte[] buffer = new byte[1024 * 1024];//設定位元組數
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
}catch (IOException e){
e.printStackTrace();
}finally{
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

第三步:web.xml 配置servlet對映

<servlet>
    <servlet-name>showImg</servlet-name>
    <servlet-class>test.ShowImage</servlet-class>
</servlet>
 
<servlet-mapping>
    <servlet-name>showImg</servlet-name>
    <url-pattern>/test/showImageServlet.do</url-pattern>
</servlet-mapping>