在同一个JSP页面中显示图像

时间:2015-10-01 10:24:59

标签: javascript java image jsp

我对后续JSP

有疑问
    <h2>Click on filename to download or Click on 'Display' link to display content</h2>
    <div id="filelist">
    <%List<String> filenames = (ArrayList<String>)request.getAttribute("filenames"); 
    if(filenames.size()>0){
        for (String filenme : filenames){       
    %>
    <div id="filename">
        <a href="javascript:submit('<%=filenme%>', 'false')" onclick="javascript:submit('<%=filenme%>', 'false')"><%=filenme%></a>  
        <div id="displink"><a href="javascript:displayContent('<%=filenme%>', 'true')" onclick="javascript:displayContent('<%=filenme%>', 'true')">Display</a></div>            
    </div><br>
    <%  }
    }%>
    </div>
    <div id="displayContent">
    </div>

这将如下所示:Output of above code.

当我点击显示链接时,它会映射到一个servlet,它会获取发送文件名的图像,并将BufferedImage写入OutputStream,如下所示:

BufferedImage bi = ImageIO.read(fs.open(item.getPath()));
if (isDisplay) {
    resp.setContentType("image/"+extn);
     ByteArrayOutputStream bas = new ByteArrayOutputStream();
    try {
        ImageIO.write(bi, extn, bas);
    } catch (IOException e) {
         e.printStackTrace();
    }

    byte[] byteArray=bas.toByteArray();
    String encdImgStr = Base64.encode(byteArray); 
    PrintWriter out = resp.getWriter();
    out.write(encdImgStr);      

我的AJAX代码是:

function displayContent(filename, isDisplay){
var ajaxRequest = getAjaxRequest();
document.getElementById("filename").value = filename;   
document.getElementById("isDisplay").value = isDisplay;

 ajaxRequest.onreadystatechange = function(){

      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('displayContent');
         ajaxDisplay.innerHTML = "<img src=\"data:image/<%=request.getAttribute(\"extn\")%>;base64," + ajaxRequest.responseText + "/>";
         document.getElementById('displayContent').style.display="block";
      }
   }
 var parameters = "filename="+filename+"&isDisplay="+isDisplay;
 ajaxRequest.open("POST", "display", true);
 ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
 ajaxRequest.send(parameters);
}

我在输出中显示字符串本身。 Output of ajax call

0 个答案:

没有答案