如何将图像作为字节数组从Angular 9发送到C#Web API核心,比如对象的属性?CRUD客户端与图像的应用
前端-角度9 后端-ASP.NET核心Web API /\ 中间件实体框架6.0 / MS SQL SERVER 1。我不知道必须在Angular中设置什么类型的对象属性? 2。如何将图像添加到对象并发送到Web Api? 3。如何在Angular应用程序中显示它们? Web API控制器帖子:如何将图像作为字节数组从Angular 9发送到C#Web API核心,比如对象的属性?CRUD客户端与图像的应用,c#,arrays,angular,image,core,C#,Arrays,Angular,Image,Core,前端-角度9 后端-ASP.NET核心Web API /\ 中间件实体框架6.0 / MS SQL SERVER 1。我不知道必须在Angular中设置什么类型的对象属性? 2。如何将图像添加到对象并发送到Web Api? 3。如何在Angular应用程序中显示它们? Web API控制器帖子: [HttpPost] public async Task<ActionResult<Leaks>> PostLeaks(Leaks leaks) {
[HttpPost]
public async Task<ActionResult<Leaks>> PostLeaks(Leaks leaks)
{
// DateTime and Username implemented to backend
DateTime curDate = DateTime.Now;
leaks.Date = curDate;
var currentUser = HttpContext.User;
string userLastname = currentUser.Claims.FirstOrDefault(c => c.Type == "lastname").Value;
leaks.Repairer = userLastname;
//
_context.Leaks.Add(leaks);
await _context.SaveChangesAsync();
return CreatedAtAction("GetLeaks", new { id = leaks.Id }, leaks);
}
MS SQLImage数据类型为varbinary(MAX)
.component.ts:
// *ngOnInit start
ngOnInit() {
//Selected options loader
this.platformsService.getAllPlatforms()
.subscribe(res => this.platforms = res as []);
this.defectslistService.getAllDefectslist()
.subscribe(res => this.defect = res as []);
// input form validation
this.leaksForm = this.formbulider.group({
Date:[null],
Sn:[null, [Validators.required]],
ShiftMI:[null, [Validators.required]],
ShiftSMT:[null, [Validators.required]],
Location:[null, [Validators.required]],
Defect:[null, [Validators.required]],
Side:[null, [Validators.required]],
AoiResult:[null],
Platform:[null, [Validators.required]],
ModelSMT:[null],
OperatorSMT:[null],
Repairer:[null],
Image:[null],
Remark:[null],
Status:[null, [Validators.required]],
});
// *load all data from Database*
this.loadallLeaks();
this.toastr.info("Init Successfully Done");
//*Angular mat-table*
this.leaksService.getAllLeaks().subscribe(list => {
let array = list.map(item => {
return { ...item };
});
this.listData = new MatTableDataSource(array);
this.listData.sort = this.sort;
this.listData.paginator = this.paginator;
this.isLoading = false;
});
//*Angular mat-table end*
}
// *ngOnInit end*
loadallLeaks() {
this.allLeaks = this.leaksService.getAllLeaks();
this.leaksService.getAllLeaks().subscribe(res => {
this.dataSource = new MatTableDataSource(res);
})
this.toastr.info("Data Was Successfully Loaded");
}
onFormSubmit() {
this.dataSaved = false;
const leaks = this.leaksForm.value;
this.CreateLeaks(leaks);
this.leaksForm.reset();
}
loadLeaksToEdit(leaksId: string) {
this.leaksService.getLeaksById('/'+leaksId).subscribe(leaks=> {
this.massage = null;
this.dataSaved = false;
this.leaksIdUpdate = leaks.Id;
this.leaksForm.controls['Sn'].setValue(leaks.Sn);
this.leaksForm.controls['Date'].setValue(leaks.Date);
this.leaksForm.controls['ShiftSMT'].setValue(leaks.ShiftSMT);
this.leaksForm.controls['ShiftMI'].setValue(leaks.ShiftSMT);
this.leaksForm.controls['Location'].setValue(leaks.Location);
this.leaksForm.controls['Defect'].setValue(leaks.Defect);
this.leaksForm.controls['Side'].setValue(leaks.Side);
this.leaksForm.controls['AoiResult'].setValue(leaks.AoiResult);
this.leaksForm.controls['Platform'].setValue(leaks.Platform);
this.leaksForm.controls['ModelSMT'].setValue(leaks.ModelSMT);
this.leaksForm.controls['OperatorSMT'].setValue(leaks.OperatorSMT);
this.leaksForm.controls['Remark'].setValue(leaks.Remark);
this.leaksForm.controls['Repairer'].setValue(leaks.Repairer);
this.leaksForm.controls['Image'].setValue(leaks.Image);
this.leaksForm.controls['Status'].setValue(leaks.Status);
});
}
CreateLeaks(leaks: Leaks) {
if (this.leaksIdUpdate == null) {
this.leaksService.createLeaks(leaks).subscribe(
() => {
this.dataSaved = true;
this.toastr.success("Record Saved Successfully");
this.loadallLeaks();
this.leaksIdUpdate = null;
this.leaksForm.reset();
} );
} else {
leaks.Id = this.leaksIdUpdate;
this.leaksService.updateLeaks(leaks).subscribe(() => {
this.dataSaved = true;
this.toastr.success("Record Updated Successfully");
this.loadallLeaks();
this.leaksIdUpdate = null;
this.leaksForm.reset();
}); }
}
deleteLeaks(leaksId: string) {
if (confirm("Are you sure you want to delete this ?")) {
this.leaksService.deleteLeaksById(leaksId).subscribe(() => {
this.dataSaved = true;
this.toastr.warning("Record Deleted Succefully");
this.loadallLeaks();
this.leaksIdUpdate = null;
this.leaksForm.reset();
}); }
}
resetForm() {
this.leaksForm.reset();
this.massage = null;
this.dataSaved = false;
this.toastr.info("Form Succefully reseted");
}
1.ts:
export class Leaks {
Id:number;
Date:string;
Sn:string;
ShiftMI:string;
ShiftSMT:string;
Location:string;
Defect:string;
Side:string;
AoiResult:string;
Platform:string;
ModelSMT:string;
OperatorSMT:string;
Repairer:string;
Image:[];
Remark:string;
Status:string;
}
非常感谢 我建议您在C#模型中使用File属性。一旦在后端(API)接收到图像,然后将其转换为字节数组,并将其保存为所需的任何位置。我相信最棘手的部分是将图像和其他属性从angular应用程序发送到WebAPI 这里有一个例子。在你的c#模型中 确保使用Microsoft.AspNetCore.Http添加
类中的代码>命名空间
角度应用
export class Leaks {
// existing properties.
Image:File;
Remark:string;
Status:string;
}
我相信您的html中必须有fileupload,因此您需要添加onChange()事件并将文件分配给模型的Image属性,或者只在componenet ex uploadedFile中创建一个变量
fileChange(fileInputEvent: any) {
this.uploadedFile = fileInputEvent.target.files[0];
}
现在打开onFormSubmit()
要发送到服务器,只需创建formdata对象,并按照您在后端对象中声明的方式填充所有属性
const formData = new FormData();
formData.append('Image', Leaks.Image, Leaks.Image.name);
formData.append('Remark', Leaks.Remarks);
-- and more properties
return this.httpClient.post<boolean>(url, formData);
const formData=new formData();
formData.append('Image',Leaks.Image,Leaks.Image.name);
formData.append('Remark',Leaks.remars);
--还有更多的财产
返回此.httpClient.post(url,formData);
在API中
[HttpPost]
public async Task<ActionResult<Leaks>> PostLeaks([FromForm]Leaks leaks)
{
// you must receive the file in leaks.Image.
// your logic to convert file to bytes.
}
[HttpPost]
公共异步任务后泄漏([FromForm]泄漏)
{
//您必须在leaks.Image中接收文件。
//将文件转换为字节的逻辑。
}
我希望它能有所帮助。我建议您在C#model中使用File属性。一旦在后端(API)接收到图像,然后将其转换为字节数组,并将其保存为所需的任何位置。我相信最棘手的部分是将图像和其他属性从angular应用程序发送到WebAPI
这里有一个例子。在你的c#模型中
确保使用Microsoft.AspNetCore.Http添加类中的代码>命名空间
角度应用
export class Leaks {
// existing properties.
Image:File;
Remark:string;
Status:string;
}
我相信您的html中必须有fileupload,因此您需要添加onChange()事件并将文件分配给模型的Image属性,或者只在componenet ex uploadedFile中创建一个变量
fileChange(fileInputEvent: any) {
this.uploadedFile = fileInputEvent.target.files[0];
}
现在打开onFormSubmit()
要发送到服务器,只需创建formdata对象,并按照您在后端对象中声明的方式填充所有属性
const formData = new FormData();
formData.append('Image', Leaks.Image, Leaks.Image.name);
formData.append('Remark', Leaks.Remarks);
-- and more properties
return this.httpClient.post<boolean>(url, formData);
const formData=new formData();
formData.append('Image',Leaks.Image,Leaks.Image.name);
formData.append('Remark',Leaks.remars);
--还有更多的财产
返回此.httpClient.post(url,formData);
在API中
[HttpPost]
public async Task<ActionResult<Leaks>> PostLeaks([FromForm]Leaks leaks)
{
// you must receive the file in leaks.Image.
// your logic to convert file to bytes.
}
[HttpPost]
公共异步任务后泄漏([FromForm]泄漏)
{
//您必须在leaks.Image中接收文件。
//将文件转换为字节的逻辑。
}
我希望有帮助