file-upload.service.ts
import { Injectable } from '@angular/core';
import { HttpService } from './http.service';
import { ApiService } from './api.service';
@Injectable({
providedIn: 'root'
})
export class FileUploadService {
constructor(
public http: HttpService,
public api: ApiService
) { }
imgUpload(imgFile: any, cb: any) {
// 图片上传
const that = this;
// 调用文件上传弹框
imgFile.nativeElement.click();
// // 2. 把获取到的图片转换成base64格式
imgFile.nativeElement.onchange = function() {
const filereader = new FileReader(); // 新建一个FileReader对象
const file = this.files[0]; // // 获取文件对象
if (!/image\/\w+/.test(file.type)) {
alert('看清楚,这个需要图片!');
return false;
}
if (this.files[0]) {
if (this.files[0].size / 1024 / 1024 > 2) {
alert('图片上传大小不要超过2MB, 请重新上传!');
return;
}
}
const imgName = file.name; // 获取文件名称
// 截取文件名称后面的文件格式
const index = imgName.lastIndexOf('.');
const Base64ImageType = imgName.substring(index + 1, imgName.length);
// 将读取的文件转换成base64格式
filereader.readAsDataURL(file);
filereader.onload = () => {
// 转换后的文件数据存储在filereader对象的result中
const result: any = filereader.result;
// 3. 图片压缩
const image = new Image(); // 新建一个img标签(不嵌入DOM节点,仅做canvas操作)
image.src = result; // 让该标签加载base64格式的原图
// 图片加载完毕后再通过canvas压缩图片,否则图片还没加载完就压缩,结果图片是全黑的
image.onload = () => {
const canvas = document.createElement('canvas'); // 创建一个canvas元素
const context = canvas.getContext('2d'); // context相当于画笔,里面有各种可以进行绘图的API
// 压缩后图片的宽度,这里设置为缩小一半,例如 imageWidth = image.width / 2;
const imageWidth = image.width;
const imageHeigth = image.height;
let imgData = ''; // 存储压缩后的图片
canvas.width = imageWidth; // 设置绘图的宽度
canvas.height = imageHeigth; // 设置绘图的高度
// 使用drawImage重新设置img标签中的图片大小,实现压缩和图片裁剪
context.drawImage(image, 0, 0, imageWidth, imageHeigth, 0, 0, 104, 104);
// 使用toDataURL将canvas上的图片转换为base64格式
imgData = canvas.toDataURL('image/jpeg');
if (imgData) {
// ajax数据请求
const params = `Base64Image=${imgData}&Base64ImageType=${Base64ImageType}`;
that.http.doPost(that.api.uploadBase64Image, params).subscribe((data: any) => {
if (data.IsSucceed) {
cb(data.Data);
} else {
alert('上传失败,请重新上传');
}
});
}
};
};
};
}
}
component.ts
// 头像上传
imgUpload() {
this.fileUpload.imgUpload(this.fileUploadImg, (imgUrl: any) => {
this.knowledgeDetail.avatorImg = imgUrl;
this.isShowAvator = true;
console.log(this.knowledgeDetail.avatorImg);
});
}
component.html
<div class="avatorImg" (click)="imgUpload()">
<div *ngIf="isShowAvator">
![在这里插入图片描述]()
</div>
<ng-container *ngIf="!isShowAvator">
<div class="ant-upload" tabindex="0" role="button">
<i class="anticon upload-icon anticon-plus ng-star-inserted">
<svg viewBox="64 64 896 896" fill="currentColor" width="1em" height="1em" data-icon="plus" aria-hidden="true"><defs><style></style></defs><path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path><path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path></svg>
</i>
<div class="ant-upload-text ng-star-inserted">上传图片</div>
</div>
</ng-container>
// 1.先通过input标签获取本地图片
<input style="display: none;" type="file" #fileUploadImg>
</div>