1、后台
@RequestMapping(value="/getPicPathByPicId/{picId}",method=RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getPicStream(@PathVariable("picId")String picId)throws IOException{
Upload sysFile = fileService.getFileById(Long.valueOf(picId));
String filePath = sysFile.getFilePath();
File file = new File(filePath);
//http头部
HttpHeaders httpHeaders = new HttpHeaders();
//application/octet-stream : 二进制流数据
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
}
2、前台
2.1、不能用ajax传输二进制流
2.2、status根据传输成功的status code决定
function picFormatter(value,row, index){
var s = '<a class = "view" href="javascript:void(0)">'+
'<img id ="imgcontainer" style="width:300;height:40px;"/></a>';
var picId = row.picture;
var url = realPath+"/xzzf/file/getPicPathByPicId/"+ picId;
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 201) {
var blob = this.response;
var img = document.getElementById("imgcontainer");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);
};
img.src = window.URL.createObjectURL(blob);
} }
xhr.send();
return [s,].join('');
}