![](/img/trans.png)
[英]asp.net core web api how to send json object from client side c#
[英]How send image as byte array from Angular 9 to C# Web API Core, like are property of object? CRUD Client aplication with image
前端 - Angular 9
后端 - ASP.NET Core Web API /\\ Middleware Entity Framework 6.0 / MS SQL SERVER
1.我不知道我必须在Angular中设置什么类型的对象属性?
2. 如何将图像添加到我的对象并将它们发送到 Web Api?
3. 我如何在 Angular 应用程序中显示它们。?
Web API 控制器 POST:
[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);
}
泄漏.cs:
public partial class Leaks
{
public int Id { get; set; }
public string Sn { get; set; }
public string ShiftSmt { get; set; }
public string ShiftMi { get; set; }
public string Location { get; set; }
public DateTime? Date { get; set; }
public string Repairer { get; set; }
public string AoiResult { get; set; }
public string OperatorSmt { get; set; }
public string ModelSmt { get; set; }
public string Platform { get; set; }
public string Remark { get; set; }
public string Defect { get; set; }
public byte[] Image { get; set; }
public string Status { get; set; }
public string Side { get; set; }
public string Extra1 { get; set; }
public string Extra2 { get; set; }
}
MS SQL图像数据类型为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");
}
泄漏.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 应用程序发送到 Web API。
这是一个例子。 在你的 C# 模型中
public partial class Leaks
{
// existing properties.
public IFormFile Image { get; set; }
}
确保using Microsoft.AspNetCore.Http;
添加using Microsoft.AspNetCore.Http;
类中的命名空间。
角度应用
export class Leaks {
// existing properties.
Image:File;
Remark:string;
Status:string;
}
我相信您的 html 中必须有 fileupload,因此您需要添加 onChange() 事件并将文件分配给模型的 Image 属性,或者只是在您的组件中创建一个变量 ex uploadFile
fileChange(fileInputEvent: any) {
this.uploadedFile = fileInputEvent.target.files[0];
}
现在 onFormSubmit()
onFormSubmit() {
this.dataSaved = false;
const leaks = this.leaksForm.value;
leaks.Image = this.uploadedFile
this.CreateLeaks(leaks);
this.leaksForm.reset();
}
并发送到服务器只需创建 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);
在您的 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.
}
我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.