2016-04-21 69 views
0

我想在我的html頁面上顯示一個圖像文件,這是我在向服務器發送JQuery post()請求後收到的,如下面的代碼所示。在post()請求後顯示圖像

我已評論我在哪裏有問題。

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> 
 
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> 
 
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> 
 

 
    <script> 
 
    $.post("http://10.10.129.164:8080/picsOnDemand/sendcphoto/cphoto", { 
 

 
     clientid: "1234567890", 
 

 
     }, 
 
     function(data) { 
 

 
     $('#blah').attr('src', data); //What should I code here? 
 

 
     }); 
 
    </script> 
 
</head> 
 

 
<body> 
 

 
    <div data-role="page"> 
 
    <div data-role="header"> 
 
     <h1>Welcome To My Homepage</h1> 
 
    </div> 
 

 
    <div id="newimage" data-role="main" class="ui-content"> 
 
     <p>I Am Now A Mobile Developer!!</p> 
 
     <img id="blah" src="" height="200" width="200" alt="Image preview..."> 
 
    </div> 
 

 
    <div data-role="footer"> 
 
     <h1>Footer Text</h1> 
 
    </div> 
 
    </div> 
 

 
</body> 
 

 
</html>

從服務器端我送響應的圖像文件,如下面的代碼:

@Path("/sendcphoto") 
public class SendCPhotoRequested { 
@POST 
@Path("/cphoto") 
@Produces("image/jpeg") 
public Response getCPhoto(@FormParam("clientid") String clientid){ 

    File file = new File("C:\\Users\\nmn\\workspace1\\clientimages\\"+clientid+".jpg"); 
    System.out.println("File sent"); 
    ResponseBuilder builder = javax.ws.rs.core.Response.ok((Object) file); 
    builder.header("Content-Disposition", "attachment; filename=clientpic.jpg"); 
    return builder.build(); 
} 
} 

請請大家幫忙,我一直在尋找這一點,但我沒有得到一個適合我的答案。

+2

您可以從服務器生成映像的URL並將其發送給響應。然後上面的代碼顯示圖像應該按預期工作。 –

+1

https://css-tricks.com/data-uris/ 看這裏,希望這有助於 –

+0

把調試器放在$('#blah')。attr('src',data)之前。並檢查控制檯中的數據對象 –

回答

1

正如Adarsh Konchady所說,您可以返回圖片的URL,以便您可以使用當前的代碼顯示它。

你也可以利用返回的data URI圖像內容爲Base64字符串和display it

$('#blah').attr('src', 'data:image/jpeg;base64, ' + data); 
+0

男人,當你只是複製評論,請至少標記爲有用 –

+1

我沒有故意複製它,我剛纔看到評論有我比我早提供的答案之一,所以我引用作者。 – Aurel

1

將圖像轉換爲base64,字符串,並將其發送到您的視圖。

Base64.encode(FileUtils.readFileToByteArray(file)); 

並簡單地在像下面的圖像src中設置base64字符串。

$('#blah').attr('src', 'data:image/jpeg;base64, ' + data);