[英]Trying to pass a model containing an IFormFile property from angular to asp.net core web api
我正在嘗試傳遞一個包含大約 8 個屬性和一個 IFormFile 屬性的 model。 當我在沒有文件的情況下傳遞 model 時,請求將正常,否則,但是當我將文件添加到 model 並嘗試發送它時,我收到一個內部服務器錯誤,描述為“錯誤:不支持接口類型的反序列化。鍵入“Microsoft.AspNetCore.Http.IFormFile”。路徑:$.corePhoto | LineNumber:0 | BytePositionInLine:173。”
Angular 14:
組件表:
userForm = this.fb.group({
userName: ['', [ Validators.required, Validators.minLength(8), Validators.maxLength(24)]],
email: ['', [ Validators.required, Validators.email]],
phoneNumber: [''],
passwordHash: ['', [ Validators.required, Validators.pattern('(?=.*[A-Za-z])(?=.*[0-9])( ?=.* [$@$!#^~%*?&,.<>"\'\\;:\{\\\}\\\[\\\]\\\|\\\+\\\-\\\=\\\_\\\)\\\(\\\)\\\`\\\/\\\\\\]])[A-Za-z0-9\d$@].{7,}'),
Validators.minLength(8), Validators.maxLength(16)]],
firstName: ['', [ Validators.minLength(3), Validators.maxLength(24)]],
lastName: ['', [ Validators.minLength(3), Validators.maxLength(24)]],
gender: [true]
}) as FormGroup;
userFormSubmition(files: any){
let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this.userService.createUser(this.userForm.value).subscribe(response => {
服務
createUser(userCreation: UserCreation){
return this.http.post(this.url + 'CreateUser', userCreation);
}
Asp.net 核心 6 web api
Model
public class ApplicationUserCreationDto : ApplicationUserDto
{
[Required]
public string UserName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string PasswordHash { get; set; }
public string PhoneNumber { get; set; }
public IFormFile CorePhoto { get; set; }
}
Controller 方法
[HttpPost]
[Route("CreateUser")]
public async Task<IActionResult> CreateUser(ApplicationUserCreationDto userCreationDto)
{
if (ModelState.IsValid)
{
//upload photo
var file = userCreationDto.CorePhoto;
var folderName = Path.Combine("Resources", "Users/Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName;
var fullPath = Path.Combine(pathToSave, fileName.ToString());
var dbPath = Path.Combine(folderName, fileName.ToString());
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
歡迎來到 Stackoverflow!
為此,您需要具有正確的 API 定義和 UI 請求。
[ApiController]
[Route("[controller]")]
public class UploadController : Controller
{
[HttpPost]
[Route("CreateUser")]
public async Task<IActionResult> CreateUser([FromForm]ApplicationUserCreationDto userCreationDto)
{
return Json(new
{
user = userCreationDto.UserName,
fileName = userCreationDto.Photo.FileName
});
}
}
public class ApplicationUserCreationDto
{
[Required]
public string UserName { get; set; }
public IFormFile Photo { get; set; }
}
Content-Type
header 等於multipart/form-data
值的請求,檢查它 in.network。 代碼可能應該是這樣的let formData = new FormData();
Object.keys(this.form.controls).forEach(formControlName => {
formData.append(formControlName, this.form.get(formControlName).value);
});
this.http.post('http://localhost:4200/api/trip',formData).subscribe(
(response) =>console.log(response),
(error) =>console.log(error)
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.