Angular + ABP 上传图片
生活随笔
收集整理的這篇文章主要介紹了
Angular + ABP 上传图片
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
angular
1,html頁(yè)面通過input上傳圖片
html:<img *ngFor="let imageItem of imageUrlList" [src]="imageItem" alt="Image"/><input nz-input type="file" name="image" accept=".jpg,.png,jpeg" (change)="handleChange($event)"/>2,ts 將上傳的文件捕獲。其中g(shù)etBase64方法讀取文件數(shù)據(jù)。sanitizer.bypassSecurityTrustUrl方法返回安全URL,預(yù)防反編譯。btoa方法將文件對(duì)象編碼為string類型保存到后端數(shù)據(jù)庫(kù)。
import { DomSanitizer, SafeUrl} from '@angular/platform-browser';constructor( private sanitizer: DomSanitizer ) {}imageUrlList: SafeUrl[] = []; objectDto: ObjectDto;handleChange(event: any ): void {if (event && event.target && event.target.files) {if (event.target.files.length === 0) {console.log('No file selected!');return;}const file = event.target.files[0];this.getBase64(file, (img: string) => {if (this.imageUrlList === undefined) {this.imageUrlList = [];}this.imageUrlList.push(this.sanitizer.bypassSecurityTrustUrl(img));if (this.objectDto.setUpPhotoList === undefined) {this.objectDto.setUpPhotoList = [];}this.objectDto.setUpPhotoList.push(btoa(img));});}}getBase64(img: File, callback: (img: string) => void): void {const reader = new FileReader();reader.addEventListener('load', () => callback(reader.result!.toString()));reader.readAsDataURL(img);}3,ts 從數(shù)據(jù)庫(kù)獲取的圖片并展示。atob方法解碼,然后輸出URL供前端img調(diào)用顯示。
if (this.objectDto.setUpPhotoList !== undefined && this.objectDto.setUpPhotoList !== null && this.objectDto.setUpPhotoList.length > 0) {this.objectDto.setUpPhotoList.forEach(item => {// 解碼const Url = atob(item);this.imageUrlList.push(this.sanitizer.bypassSecurityTrustUrl(Url));}) }ABP
1,實(shí)例中Dto和Entity的屬性值相同,可以使用autoMap標(biāo)簽自動(dòng)映射。SetUpPhotoList 的類型是List<string>,圖片在數(shù)據(jù)庫(kù)中的保存類型為string類型。
public class objectDto{public List<string> SetUpPhotoList { get; set; }}public class objectEntity{public List<string> SetUpPhotoList { get; set; }}2,配置文件如下,在保存到數(shù)據(jù)庫(kù)時(shí)將List<string>序列化,讀取數(shù)據(jù)庫(kù)時(shí)再反序列化。
public class objectEntityConfiguration : IEntityTypeConfiguration<objectEntity>{public void Configure(EntityTypeBuilder<objectEntity> builder){builder.ToTable("objectEntity");builder.Property(p => p.SetUpPhotoList).HasConversion(v => JsonConvert.SerializeObject(v),v => JsonConvert.DeserializeObject<List<string>>(v));}}?
總結(jié)
以上是生活随笔為你收集整理的Angular + ABP 上传图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么Vue在国际上越来越没影响力?
- 下一篇: 下半年十大勒索攻击盘点、德国某医疗系统存