angular图片上传,只要屡清楚了思路,敲代码会非常顺畅.
先分享一下图片上传的思路.
首先在HTML写好图片上传的触发事件,触发之后,开始调ts中的方法,就是走代码中的上传图片,selectedFileOnChanged(),把图片上传的服务器上边,然后返回一个图片的地址,放到pictureURL里,然后点击确定报错pictureURL地址到数据库.
html代码
<img src="{{defaultPicture}}" class="center-img" id="wizardPicturePreview" title="" />
<input #file type="file" name='file' id="wizard-picture" ng2FileSelect [uploader]="uploader" class="showPicture" (change)="selectedFileOnChanged()">
ts代码
// 上传图片
public selectedFileOnChanged() {
this.editPicture = !this.editPicture;
let obj=this;
const options = {
url: this.http.getServerUrl("graduate-web/picture/FileUploads"),
method: "POST",
removeAfterUpload: true,
itemAlias: 'multipart/form-data',
allowedFileType: ["image"]
}
this.uploader.setOptions(options);
console.log(this.uploader.queue.length);
if (this.uploader.queue.length > 0) {
// 上传
this.uploader.queue[this.uploader.queue.length - 1].onSuccess = function (response, status, headers) {
// 上传文件成功
if (status == 200) {
// 上传文件后获取服务器返回的数据
let tempRes = JSON.parse(response);
// 修改页面图片
let pictureURL = tempRes.data;
//this.picAllUrls=tempRes.data
const picServerUrl: string = "http://192.168.22.64/";
// const el3: Element = document.getElementById('picServerUrl');
console.log(pictureURL);
const el: Element = document.getElementById('wizardPicturePreview');
el.setAttribute('src', picServerUrl + pictureURL);
const el2: Element = document.getElementById('wizard-picture');
el2.setAttribute('class', 'hidePicture');
// 存储图片路径
obj.pictureUrls.push(pictureURL);
} else {
// 上传文件后获取服务器返回的数据错误
this.msgs = [{
severity: 'error',
summary: '提示',
detail: '上传图片失败'
}];
}
};
this.uploader.queue[this.uploader.queue.length - 1].upload();// 开始上传
}
}
//保存图片
let url: string = 'graduate-web/education/addEducationList/';
this.educationEntity.operator = localStorage.getItem('userName'); //获取操作人-hgt-2018年3月7日
this.educationEntity.operatorId = localStorage.getItem('userId'); //获得登录用户的id作为操作人的id-hgt-2018年3月7日
this.educationEntity.pictureUrls = this.pictureUrls;
// let nowdate=new Date();
// this.educationEntity.createTime = this.translateTime(new Date(nowdate)); //转换时间格式-haoguiting-2018年3月15日
this.educationEntity.userId = this.userId;
let array = new Array();
array.push(this.educationEntity);
let body = JSON.stringify(array);
this.http.post(url, body).toPromise().then(
res => {
if (res.json().code == "0000") {
this.router.navigateByUrl("workspace/education");
this.showDialog(res.json().message);
}
else {
}
最后附上一张图片,效果还是非常好的.