先写一个方法把图片转换成64位字符串 public static String getImgPath(String ImgPath) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(ImgPath); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 加密 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }
//下面就是升级版的
@RequestMapping("/preview/{id}")
@ResponseBody
public List preview(HttpServletRequest request,@PathVariable("fid") Integer fid){
List<Picture> picture= new ArrayList<Picture>();
List<byte[]> list=new ArrayList<byte[]>();
InputStream inputStream = null;
byte[] datas = null;
try {
if(fid==null){
picture=null;
}else{
picture=pictureService.selectPicture(fid);
if(picture!=null){
//循环把图片转换成64位字符串
for (int j = 0; j < picture.size(); j++) {
inputStream = new FileInputStream(picture.get(j).getFilePath());
datas = new byte[inputStream.available()];
inputStream.read(datas);
//把64位字符串存入list中
list.add(datas);
inputStream.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
//直接返回list
return list;
}
//在js中循环生成图片。
$.ajax({
type: 'post',
url: "/file/preview+"/"+id",
dataType: 'json',
data: formData,
async: true,
cache: false,
success: function(list) {
var imgListBox = $(".xxxx");
var content = " ";
for (var i = 0; i < list.length; i++) {
<img src=" + "data:image/png;base64," + list[i] + ">
}
imgListBox.append(content);
}error: function() {
toastr.error("Upload failed");
}
});