angular
1,html页面通过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 将上传的文件捕获。其中getBase64方法读取文件数据。sanitizer.bypassSecurityTrustUrl方法返回安全URL,预防反编译。btoa方法将文件对象编码为string类型保存到后端数据库。
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 从数据库获取的图片并展示。atob方法解码,然后输出URL供前端img调用显示。
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,实例中Dto和Entity的属性值相同,可以使用autoMap标签自动映射。SetUpPhotoList 的类型是List<string>,图片在数据库中的保存类型为string类型。
public class objectDto
{
public List<string> SetUpPhotoList { get; set; }
}
public class objectEntity
{
public List<string> SetUpPhotoList { get; set; }
}
2,配置文件如下,在保存到数据库时将List<string>序列化,读取数据库时再反序列化。
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));
}
}