手机端项目组中有上传图片的功能,也是鼓捣了好久才实现,记录一下整个过程,方便以后的复用。
1、上传图片需要引入第三方的插件,安装命令为:
npm install ng2-file-upload --save
2、在需要上传图片的页面的module.ts文件中加入依赖:
PS:若不加依赖,则会报下面的错
3、在ts文件中加入依赖:
在ts文件中声明FileUploader类型的变量:
export class UploadofferPage extends BaseUI implements OnInit {
public uploadUrl = environment.NO1SystemURL + 'NO1/FastDFS/UploadPhoto';
// 声明一个FileUploader类型的变量,并将其初始化 用于图片上传-温娉哲-2019年5月23日08:43:43
public uploader: FileUploader = new FileUploader({
// 声明一个FileUploader类型的变量,并将其初始化
url: environment.NO1SystemURL + '/NO1/FastDFS/UploadPhoto',
// url: "NO1System/NO1/FastDFS/UploadPhoto",
method: 'POST',
// autoUpload: true,
removeAfterUpload: true,
itemAlias: 'multfile',
// allowedFileType: ['image']
});
}
4、上传图片的HTML页面:
<!-- 图片上传 -->
<div class="item act-cell-padding" [(ngModel)]="offerurl" style="margin-left: 5%;margin-right: 5%; text-align: center; width: 200px;height: 200px">
<div class="picPlace" style="text-align: center; width: 200px;height: 200px">
<img id="wizardPicturePreview" name="picture" src="{{picture}}" style="text-align: center; display:block;border:1px solid #CCC ;width: 200px;height: 200px" alt=""
title=""/>
<input #file type="file" id="file" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged(file)">
</div>
</div>
上传图片的input框中绑定上传图片的change事件 selectedFileOnChanged(file),页面上传图片,上传的图片发送给fastDFS处理,接收返回的图片地址,HTML页面中绑定图片的id,返回的地址给绑定的id从而实现页面图片的显示。
// 选择上传图片-温娉哲-2019年5月23日08:41:05
public selectedFileOnChanged(file: HTMLInputElement) {
let length: number;
let newurl: any;
this.editPicture = !this.editPicture;
this.fileName = file.value;
const fileDot: string = this.fileName.substring(this.fileName.lastIndexOf('.') + 1, this.fileName.length);
localStorage.setItem('offerurl', this.fileName); // 将图片地址存到缓存中
this.uploader.onBeforeUploadItem = (item => {
item.withCredentials = false;
});
// 开始上传
this.uploader.queue[0].upload();
this.uploader.queue[0].onSuccess = function (response, status, headers) {
// headers.header('Access-Control-Allow-Origin', '*');
console.log(response);
// 上传文件成功
if (status === 200) {
// 上传文件后获取服务器返回的数据
const temRes = JSON.parse(response);
const a = temRes.substr(1, response.length);
// const a = temRes.split('\',\'');
localStorage.setItem('offerpicurl', a); // 将地址存到表里
// let newurl = temRes.data;
length = temRes.length;
console.log(length);
newurl = temRes.substring(21, length - 1);
this.picture = newurl;
localStorage.setItem('offerpicurl', 'http://192.168.22.78' + newurl);
// 修改页面图片
const el: Element = document.getElementById('wizardPicturePreview');
el.setAttribute('src', localStorage.getItem('offerpicurl'));
} else {
alert('上传图片失败');
}
};
}
特别注意:虽然我们的后端中配置了跨域,但是前端处理上传图片这块还是会报跨域问题。如果上传图片的方法中不配置跨域,会报CORS同源策略跨域的问题。
this.uploader.onBeforeUploadItem = (item => {
item.withCredentials = false;
});
报错的问题显示: