【Java】web實現圖片在線預覽


一.場景還原

用戶上傳了一張圖片,已有服務器保存路徑,現由於系統配置無法直接通過圖片URL打開預覽圖片,需實現點擊預覽將圖片顯示在瀏覽器上。

二.實現方法

html:

    <a href="##" onclick="preview('${file.filePath}')" >預覽</a>

此處用預覽按鈕方法實現

Javascript:

function preview(path){
    var ext=path.split('.')[1];
    if(ext=="PNG"){
        window.open("<%=path%>/file/showImage.do?path="+path);
    }
}

此處因為測試判斷了PNG

Java:

/*
     * 在線預覽圖片
     */
    @RequestMapping("/showImage.do")
    public @ResponseBody
    void showImage(String path) throws IOException {
        getResponse().setContentType("text/html; charset=UTF-8");
        getResponse().setContentType("image/jpeg");
        String fullFileName = getRealPath("/upload/" + path);
        FileInputStream fis = new FileInputStream(fullFileName);
        OutputStream os = getResponse().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();
        }
    }

三.執行結果

打開一個新的窗口,顯示圖片。

 

 

本文為博主原創文章

轉載請保留出處:http://www.cnblogs.com/zwqh/p/6494839.html 
謝謝合作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM