如何在 JSON 中写入编码流并在 ajax 中检索?
how to write encoded stream in JSON and retrieve back in ajax?
我正在获取输入流中的图像并将其编码为 base64,然后使用 JSON 将其发送给客户端
以下是代码片段。
服务器端:
JsonObject myObj = new JsonObject();
StringBuilder responseStrBuilder = new StringBuilder();
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
responseStrBuilder.append(encoder.encode(contents).getBytes());
}
myObj.addProperty("1",responseStrBuilder.toString());
out.println(myObj.toString());
客户端ajax代码:
success: function(result)
{
if(result)
{
$('#dynamicCamping01').html('<img src='+result[Object.keys(result)[0]]+'/>');
$('#dynamicCampingDesc01').html("<h3>"+allData[0]+"</h3>");
}
else
{
alert("Something went wrong while retriving events");
}
正在客户端获取数据但未显示图像。
这个有效:
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
bout.write(encoder.encode(contents).getBytes());
}
bout.close();
fin.close();
bin.close();
out.close();
主要的重要部分是在客户端将图像转换为 UTF-8 和 Base64 解码。
$(imageIDSData[i]).html('<img src="data:image/jpeg;charset=utf-8;base64,'+imageData[i]+'"/> ');
$(imageNameIDSData[i]).html("<h3>"+allData[i]+"</h3>");
我正在获取输入流中的图像并将其编码为 base64,然后使用 JSON 将其发送给客户端 以下是代码片段。
服务器端:
JsonObject myObj = new JsonObject();
StringBuilder responseStrBuilder = new StringBuilder();
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
responseStrBuilder.append(encoder.encode(contents).getBytes());
}
myObj.addProperty("1",responseStrBuilder.toString());
out.println(myObj.toString());
客户端ajax代码:
success: function(result)
{
if(result)
{
$('#dynamicCamping01').html('<img src='+result[Object.keys(result)[0]]+'/>');
$('#dynamicCampingDesc01').html("<h3>"+allData[0]+"</h3>");
}
else
{
alert("Something went wrong while retriving events");
}
正在客户端获取数据但未显示图像。
这个有效:
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
bout.write(encoder.encode(contents).getBytes());
}
bout.close();
fin.close();
bin.close();
out.close();
主要的重要部分是在客户端将图像转换为 UTF-8 和 Base64 解码。
$(imageIDSData[i]).html('<img src="data:image/jpeg;charset=utf-8;base64,'+imageData[i]+'"/> ');
$(imageNameIDSData[i]).html("<h3>"+allData[i]+"</h3>");