html代码:
<div style="float: left">
<!-- 图片展示按钮 -->
<button class="myBtn4">
确认展示
</button>
</div>
<div id="d1" class="Z_slider">
</div>
js代码:
细节说明:
// 错误写法 (不可直接将blob加载到img中,由于blob太大,会有性能影响,所以先释放)
var img = document.createElement("img");
img.src = window.URL.createObjectURL(blob);
//正确写法
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); //释放
};
img.src = window.URL.createObjectURL(blob);
$("#d1").html(img);
$(function() {
$('.myBtn4').on('click', function(){
var url = "/项目名/homepage/showPic";
var xhr = new XMLHttpRequest(); //创建 XMLHttpRequest 对象
xhr.open('POST', url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("client_type", "DESKTOP_WEB");
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);//释放
};
img.src = window.URL.createObjectURL(blob);
$("#d1").html(img);
}
}
xhr.send();
})
})
java代码:
@Override
public void showPic(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException, InterruptedException {
Configuration conf = new Configuration();
String uri="hdfs://192.168.248.147:9000/yttlj/input/2.jpg";
Path _file = new Path(uri);
FileSystem hdfs = FileSystem.get(URI.create(uri),conf, "root");
FileStatus status = hdfs.getFileStatus(_file);
//获取输入流
FSDataInputStream fis = hdfs.open(_file);
response.setHeader("Content-Type", "image/jpeg");
response.setHeader("Content-Length", String.valueOf(status.getLen()));
BufferedOutputStream output = null;
output = new BufferedOutputStream(response.getOutputStream());
byte [] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
//使用 BufferedOutputStream 最后要利用 flush 将 buffer 数据送出去
output.flush();
fis.close();
}
结果展示: