【发布时间】:2020-07-13 16:01:36
【问题描述】:
我有一个员工模型和头像。我需要在一种 POST 方法中上传个人资料图片和模型日期。我只需要将图像文件名保存在数据库中并在 WebRoot 目录中上传图像。
这是我的模型: 公共部分类雇主
{
public int EmployerId { get; set; }
public string Companyname { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Password { get; set; }
public string DisplayImage { get; set; }
public bool? IsActive { get; set; }
public DateTime StateDate { get; set; }
}
这是我的控制器代码:
[HttpPost]
public async Task<ActionResult<Employees>> PostEmployees([FromForm] FileUploadAPI Image, [FromBody]Employees employees)
{
try
{
_context.Employees.Add(employees);
await _context.SaveChangesAsync();
await UploadImage(Image, 2, employees.EmployeeId);
var returnInfo = CreatedAtAction("GetEmployees", new { id = employees.EmployeeId }, employees);
return returnInfo;
}
catch(Exception ex)
{
return NoContent();
}
}
public class FileUploadAPI
{
public IFormFile files { get; set; }
}
public async Task<string> UploadImage(FileUploadAPI files, int UserType, int UserId)
{
if (files.files.Length > 0)
{
try
{
if (!Directory.Exists(_hostingEnvironment.WebRootPath + "\\Employees\\"))
{
Directory.CreateDirectory(_hostingEnvironment.WebRootPath + "\\Employees\\");
}
Guid guid = Guid.NewGuid();
string filename = _hostingEnvironment.WebRootPath + "\\Employees\\" + $"EM-{UserType}-UserId-{guid}";
using (FileStream filestream = System.IO.File.Create(filename))
{
await files.files.CopyToAsync(filestream);
filestream.Flush();
return filename;
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
else
{
return "Not Found";
}
}
如果我只是在没有员工模型的情况下在 POSTMAN 中上传文件,它工作正常。但是当我同时传递两个文件员工数据时,文件返回空值。
任何建议,解决方案?
谢谢
【问题讨论】:
-
嗨@Jognu Khan,我的回答对您解决问题有帮助吗?如果是。请您接受作为答案吗?参考:How to accept as answer。如果不是,请跟进让我知道。
标签: asp.net-core