声明:本篇所采用方法也是从各个处习得
页面效果预览:
实现代码及常见问题
1.上传按钮
功能描述:点击弹出上传的从窗体,并进行过图片的上传
实现步骤:1.制作表单 2.提交数据
示例代码:(样式忽略,只注重数据的传递交互)
js:(ajax发送含有文件(图片)的表单数据)
//实现照片上传功能
uploadphoto: function() {
vm.centerDialogVisible = true;//控制悬浮窗口是否弹出标志
this.getCurTime();
this.getPhotoId();
},
//上传表单内容检验
upload: function() {
var photoid1 = $("#photoid").val();
console.log(photoid1)
var ryid1 = $("#ryid").val();
var filename1 = $("#filename").val();
var uploadname1 = $("#uploadname").val();
if (photoid1 == null || photoid1 == "") {
alert("照片id不能为空");
return false;
} else if (ryid1 == null || ryid1 == "") {
alert("人员id不能为空");
return false;
} else if (filename1 == null || filename1 == "") {
alert("请选择你要上传的照片");
return false;
} else if (uploadname1 == null || uploadname1 == "") {
alert("上传人不能为空");
return false;
} else {
console.log("数据完备")
}
//ajax如何向后台发送含有带有文件的表单数据
let formData = new FormData($('#photoData')[0]);
$.ajax({
type: "post",
url: sysConfig.servicePath + "human/staffphotomanage/upload",
data: formData,
cache: false,
async: false,
processData: false,
contentType: false,
success: function(obj) {
if (obj.msg == "ok") {
vm.$alert("保存数据成功!", "提示");
vm.centerDialogVisible = false;
} else {
vm.$alert("保存数据失败!", "提示");
}
},
error: function(obj) {
vm.$alert("保存数据失败!", "提示");
}
});
this.exit();
this.photoQuery();
},
java:(接收ajax发送的带有文件的表单数据,图片的上传)
@RequestMapping("/staffphotomanage/upload")
@ResponseBody
public Result upload( MultipartHttpServletRequest uploadData) throws ParseException, IOException {
MultipartFile photo=uploadData.getFile("filename");
/**
* 上传图片
*/
//图片上传成功后将图片的地址写到数据库
File pathFile = new File(".\\src\\main\\java\\com\\casit\\staffPhoto");
String filePath=pathFile.getAbsolutePath();;//保存图片的路径
System.out.println(filePath);
String fileName=photo.getOriginalFilename();//获取原始图片的拓展名
String newFileName= UUID.randomUUID()+fileName;//新的文件名字
//封装上传文件位置的全路径
File targetFile=new File(filePath,newFileName);
String path=filePath+"\\"+newFileName;
System.out.println(path);
//把本地文件上传到封装上传位置的全路径
photo.transferTo(targetFile);
//获取前端输送的信息重组对象
staffPhoto.setCertId(Integer.parseInt(uploadData.getParameter("photoid")));
staffPhoto.setRs_ryjcxx_id(Integer.parseInt(uploadData.getParameter("ryid")));
staffPhoto.setDataType(uploadData.getParameter("dataType"));
staffPhoto.setCertpath(path);
staffPhoto.setFileName(fileName);
staffPhoto.setMaker(Integer.parseInt(uploadData.getParameter("uploadname")));
//将时间字符串转换为时间类型
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
String time=uploadData.getParameter("uploadtime");
System.out.println(time);
staffPhoto.setMakedate(sdf.parse(time));
staffPhoto.setMemo(uploadData.getParameter("memo"));
int no=Integer.parseInt(uploadData.getParameter("photoid"))-1000;
staffPhoto.setSortno(no);
String info = "";
try {
staffPhotoManageService.insertStaffPhoto(staffPhoto);
info = "ok";
} catch (Exception e) {
info = "error";
e.printStackTrace();
}
return Result.success(info, "", 1);
}
2.删除按钮
功能描述:选中数据行,点击从数据库删除
示例代码:(样式忽略,只注重数据的传递交互)
js:()
//删除事件具体实现
photoDelete: function() {
var id = (this.currentRow.certId).toString();
var filepath=this.currentRow.certpath;
console.log(id);
vm.dataCache.addDelete(this.currentRow);
if (id != null) {
$.ajax({
url: sysConfig.servicePath + "human/staffphotomanage/delete",
data: {
id: id,
path:filepath
},
type: "post",
success: function(obj) {
if (obj.msg == "success") {
vm.$alert("数据删除成功!", "提示");
vm.dataCache.clearAll();
HeyiUtil.removeArrayByObject(vm.tableData, vm.currentRow);
} else {
vm.$alert("数据删除失败!", "提示");
}
},
error: function() {
vm.$alert("数据删除失败!", "提示");
vm.centerDialogVisible = false;
}
});
vm.centerDeleteVisible = false;
} else {
HeyiUtil.removeArrayByObject(vm.tableData, vm.currentRow);
}
},
java:
@RequestMapping("/staffphotomanage/delete")
@ResponseBody
public Result delete(@RequestParam Map<String,String> data){
String id=null;
String path=null;
for (Map.Entry<String,String> entry : data.entrySet()) {
if(entry.getKey().equals("id")){
id = entry.getValue();
}else{
path=entry.getValue();
}
System.out.println("Key = " + entry.getKey() + ",value=" + entry.getValue());
}
System.out.println(id);
System.out.println(path);
//调用方法真实的从图片存放文件删除数据
deleteimg(path);
//从数据库删除图片信息
int photoId=Integer.parseInt(id);
String info = "";
try {
staffPhotoManageService.deleteStaffPhoto(photoId);
info = "success";
} catch (Exception e) {
info = "error";
e.printStackTrace();
}
return Result.success(info,"",1);
}
//删除本地目录存储的上传照片
//工具方法:从文件真实删除图片
private static void deleteimg(String path){
boolean flag=false;
if (!flag ) {
System.out.println("删除图片开始");
flag = true;
System.out.println("开始执行,图片路径为"+path);
File file = new File(path);
//判断文件是否存在
if (file.exists() == true){
System.out.println("图片存在,可执行删除操作");
Boolean or = false;
or = file.delete();
if (flag){
System.out.println("成功删除图片"+file.getName());
}else {
System.out.println("删除失败");
}
}else {
System.out.println("图片不存在,终止操作");
}
}
}
3.更新按钮
参考上传
4.保存按钮数据上传功能
5.下载按钮
//下载图片按钮(通过base64实现图片的下载)-------------------------------------------
download: function() {
if (!this.currentRow) {
this.$alert("请选择你要要下载的数据行!", "提示");
return;
}
var url = this.currentRow.certpath;
var imgname = this.currentRow.fileName;
var string = document.getElementById("picture").src;
console.log(string);
this.downloadFile1(imgname, string);
},
downloadFile1: function(imgname, imgUrl) {
// 这里是获取到的图片base64编码,这里只是个例子哈,要自行编码图片替换这里才能测试看到效果
// 如果浏览器支持msSaveOrOpenBlob方法(也就是使用IE浏览器的时候),那么调用该方法去下载图片
if (window.navigator.msSaveBlob) {
var bstr = atob(imgUrl.split(',')[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
var blob = new Blob([u8arr])
window.navigator.msSaveBlob(blob, imgname)
} else {
// 这里就按照chrome等新版浏览器来处理
const a = document.createElement('a')
a.href = imgUrl
a.setAttribute('download', imgname)
a.click()
}
},
6.点击数据行同步预览图片
rowdblClick: function(row, column, event) {
this.dataCache.addUpdate(row);
vm.staffPhoto = row;
var path = vm.staffPhoto.certpath;
//实现根据路径查询图片呢
$.ajax({
url: sysConfig.servicePath + "human/staffphotomanage/photo",
data: {
key: path
},
type: "post",
success: function(result) {
if (result != null) {
$("#picture").attr("src", result);
} else {
vm.$alert("查询失败!", "提示");
}
},
error: function() {
vm.$alert("查询失败!", "提示");
}
});
},
@RequestMapping("/staffphotomanage/photo")
@ResponseBody
public String photo(@RequestParam() Map<String,String> data){
String path="";//接受前台传过来的路径
String imgStr = "";//返回经过编码的图片数据
//System.out.println(data);
for (Map.Entry<String,String> entry : data.entrySet()) {
System.out.println("Key = " + entry.getKey() + ",value=" + entry.getValue());
path=entry.getValue();
}
System.out.println("路径:"+path);
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
int offset = 0;
int numRead = 0;
while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fis.close();
BASE64Encoder encoder = new BASE64Encoder();
imgStr = encoder.encode(buffer);
} catch (Exception e) {
e.printStackTrace();
}
return "data:image/png;base64,"+imgStr;
}