我创建了一个API,以将文件上传到dotnet核心。
[HttpPost("uploads")]
public async Task<IActionResult> PostUploads(IFormFile filedata)
{
if (filedata == null) return BadRequest("Null File");
if (filedata.Length == 0)
{
return BadRequest("Empty File");
}
if (filedata.Length > 10 * 1024 * 1024) return BadRequest("Max file size exceeded.");
if (!ACCEPTED_FILE_TYPES.Any(s => s == Path.GetExtension(filedata.FileName).ToLower())) return BadRequest("Invalid file type.");
var uploadFilesPath = Path.Combine(environment.WebRootPath, "uploads");
if (!Directory.Exists(uploadFilesPath))
Directory.CreateDirectory(uploadFilesPath);
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(filedata.FileName);
var filePath = Path.Combine(uploadFilesPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await filedata.CopyToAsync(stream);
}
var photo = new FileUploadAttachment { Name = fileName };
var filePaths = new FileUploadAttachment { FilePath = filePath };
_GpsContext.FileUploadAttachments.Add(photo);
_GpsContext.FileUploadAttachments.Add(filePaths);
await _GpsContext.SaveChangesAsync();
return Ok();
}
我想使用创建实体时获得的一些ID改进数据库中的代码和存储。我的实体框架表如下所示:
public class FileUploadAttachment
{
public Guid Id { get; set; }
public string Name { get; set; }
public string FileTypeExt { get; set; }
public string FilePath { get; set; }
public string EntityName { get; set; }
public Guid? EntityId { get; set; }
}
我使用相同的映射创建了View模型,该模型可以在JSON中显示上述代码字段。视图模型的结构链接如下:
public class FilesVm
{
public string Id { get; set; }
public string Name { get; set; }
public string FileTypeExt { get; set; }
public string FilePath { get; set; }
public string EntityName { get; set; } // This is value will get from screen where the file will be upload
public Guid? EntityId { get; set; } // This id will get from the screen where it will be created.
}
如何在控制器中实现此视图模型。