我創建了一個 API,它正在資料庫中添加資料,包括值和影像。
在郵遞員中,我正在呼叫它并在表單資料中設定影像,并在 JSON 中設定原始值中的其他值,但仍然在影像中我在源代碼物件中獲得空值。下面是截圖。
我需要兩方面的幫助:
- 為什么我在源代碼中的影像值為 Null,請檢查下圖。
- 如何使用郵遞員發送影像和資料,檢查下面的截圖是否我嘗試過?
第一個螢屏截圖是郵遞員,我以 json 格式發送資料:

第二個截圖是郵遞員,我在郵遞員的同一請求中發送影像

現在在第三張圖片中,您可以在 Image 中看到它顯示的是 Null 而不是值。

所以我不明白為什么影像變為空..下面是這個代碼
public async Task<int> Create(UserPreference _object)
{
if(_object.Image != null)
{
var webRootPath = hostingEnv.WebRootPath;
var fileName = Path.GetFileName(_object.Image.FileName);
var filePath = Path.Combine(hostingEnv.WebRootPath, "images\\User", fileName);
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
await _object.Image.CopyToAsync(fileStream);
}
_object.ImagePath = filePath;
}
var obj = await applicationDbContext.UserPreferences.AddAsync(_object);
return applicationDbContext.SaveChanges();
}

[HttpPost]
[Route("CreateUserPreference")]
public async Task<ActionResult> CreateUserPreference([FromBody] UserPreference userPreference)
{
if (ModelState.IsValid)
{
try
{
var userPreferenceId = await _userPreference.Create(userPreference);
if (userPreferenceId > 0)
return Ok("User Preference has added");
}
catch(Exception)
{
return BadRequest();
}
}
return BadRequest();
}
[Display(Name = "Name")]
public string Name { get; set; } = "";
[Display(Name = "Location")]
public string Location { get; set; } = "";
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "About Me")]
public string AboutMe { get; set; } = "";
[Display(Name = "Match Preference")]
public string MatchPreference { get; set; } = "";
[Display(Name = "Play Score")]
public string PlayScore { get; set; } = "";
[Display(Name = "Location")]
public string LocationPreference { get; set; } = "";
[Display(Name = "CreatedOn"), DataType(DataType.Date)]
public DateTime CreatedOn { get; set; } = DateTime.Now;
[Display(Name ="Upload Photo")]
public string ImagePath { get; set; } = "";
[NotMapped]
public IFormFile Image { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
public virtual User User { get; set; }
uj5u.com熱心網友回復:
您不能同時發送表單資料和 JSON 正文為了解決您的問題將影像和其他資訊作為表單日期發送有關更多詳細資訊,請參閱螢屏截圖
uj5u.com熱心網友回復:
要使用 Postman 發送影像和資料,您必須使用表單資料內容型別。
選擇正文 => 表單資料。列鍵有一個選擇器。對于檔案,選擇檔案型別并選擇檔案。要同時發送資料,您必須在鍵值對中將 json 分開。
并從動作中洗掉 [FromBody] 屬性。它只用于 Content-Type: application/json,但你的 Content-Type: multipart/form-data;
uj5u.com熱心網友回復:
郵遞員不允許您像這樣同時發送兩種不同的表單型別。您的問題是發送 JSON 有效負載或影像的二進制內容。
因此,相反,將檔案和JSON 有效負載添加到表單資料螢屏,如下所示:

Postman 將自動設定Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW標題,然后像這樣處理實際的正文:
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename="/C:/Users/xyz/Downloads/hystrix-dashboard-netflix-api-example-iPad.png"
Content-Type: image/png
(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/366918.html
標籤:C# asp.net核心 .net核心 asp.net-web-api 邮差
