1. 程式人生 > >後臺根據地址傳輸二進位制流,前臺顯示圖片

後臺根據地址傳輸二進位制流,前臺顯示圖片

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('');
     	  
        }