Nic*_*Nic 5 c# asp.net-web-api postman .net-core asp.net-core
我创建了一个 API,它正在数据库中添加数据,包括值和图像。
在邮递员中,我调用它并在表单数据中设置图像,并在 JSON 中设置原始值,但仍在图像中,我在源代码对象中获取空值。以下是屏幕截图。
我需要两件事上的帮助:
第一个屏幕截图是邮递员,其中我以 json 格式发送数据:
第二个屏幕截图是邮递员,其中我在邮递员中的同一请求中发送图像
现在,在第三张图片中,您可以在图片中看到它显示的是 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();
}
Run Code Online (Sandbox Code Playgroud)
[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; }
Run Code Online (Sandbox Code Playgroud)
小智 5
Postman允许将混合数据类型发布为 Multipart/form-data,您只需选择显示内容类型的选项:
那么你可以使用控制器(这里是java中的示例):
@PostMapping(value = "store/template", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public void createDocumentTemplate(@Valid @RequestPart("templateRequest") TemplateDto request, @Valid @RequestPart("file") MultipartFile file) {
storeYourFileAccordingToYourRequest(request, file);
}
Run Code Online (Sandbox Code Playgroud)
要使用 Postman 发送图像和数据,您必须使用表单数据内容类型。
选择正文 => 表单数据。列键有一个选择器。对于文件,选择文件类型并选择文件。要同时发送数据,您必须将 json 键值对分开。
并从操作中删除 [FromBody] 属性。它仅用于Content-Type:application/json,但是您的Content-Type:multipart/form-data;
归档时间: |
|
查看次数: |
11065 次 |
最近记录: |