閱讀881 返回首頁    go 阿裏雲 go 技術社區[雲棲]


JavaWeb將圖片顯示在瀏覽器中

一、背景
用戶上傳了一張圖片,圖片到服務器後用戶得到一個鏈接,可以將圖片顯示在瀏覽器上。

二、實現
假設項目名叫TestProject,文件放在項目根目錄下的uploadImages文件夾下。
①圖片名為英文,可直接通過鏈接打開圖片
<a href="https://localhost:8080/TestProject/uploadImages/myImage.jpg">預覽圖片</a>

②圖片名含有中文,通過Servlet將圖片輸出到瀏覽器上,使用圖片在服務器上的絕對路徑
showImage.jsp
<a href="/TestProject/showImageServlet?filename=測試的圖片一枚.jpg">預覽圖片</a>

showImageServlet
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
String fname = request.getParameter("filename");
String newpath = new String(fname.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();
}
}

最後更新:2017-04-03 12:55:02

  上一篇:go 簡單的Android之apk包反編譯方法
  下一篇:go Android TextView中文字通過SpannableString來設置超鏈接、顏色、字體等屬性