我创建了一个采用任意文件的端点:
[HttpPost()]
public async Task<IActionResult> CreateFile(IFormFile file)
当我使用Postman测试时,file
始终为空。
以下是我在Postman中所做的事情:
我做错了什么?
答案 0 :(得分:18)
答案 1 :(得分:6)
一个或多个文件上传的完整解决方案如下所示:
此操作用于上传多个文件:
// Of course this action exist in microsoft docs and you can read it.
HttpPost("UploadMultipleFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// Full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
using (var stream = new FileStream(filePath, FileMode.Create))
await formFile.CopyToAsync(stream);
}
// Process uploaded files
return Ok(new { count = files.Count, path = filePath});
}
此操作用于上传单个文件:
[HttpPost("UploadSingleFile")]
public async Task<IActionResult> Post(IFormFile file)
{
// Full path to file in temp location
var filePath = Path.GetTempFileName();
if (file.Length > 0)
using (var stream = new FileStream(filePath, FileMode.Create))
await file.CopyToAsync(stream);
// Process uploaded files
return Ok(new { count = 1, path = filePath});
}
答案 2 :(得分:1)
您应该是这样
[HttpPost]
public async Task<IActionResult> UploadFile([FromForm]UploadFile updateTenantRequest)
{
}
您的课程应该像:-
public class UpdateTenantRequestdto
{
public IFormFile TenantLogo { get; set; }
}
答案 3 :(得分:1)
[HttpPost("UploadSingleFile"), Route("[action]")]
public async Task<IActionResult> UploadSingleFile([FromForm(Name = "file")] IFormFile file)
{
// Process uploaded files
string folderName = "Uploads";
string webRootPath = hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
Repository.Models.File fileModel = new Repository.Models.File();
fileModel.Name = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
fileModel.Path = $"{folderName}/{file.FileName}";
fileModel.Size = file.Length;
fileModel.Type = file.ContentType;
string fullPath = Path.Combine(newPath, fileModel.Name);
fileModel.Extension = Path.GetExtension(fullPath);
fileModel.CreatedDate = Utility.Common.GetDate;
fileModel.CreatedBy = 1;
//fileModel save to db
using (var stream = new FileStream(fullPath, FileMode.Create))
{
//file.CopyTo(stream);
await file.CopyToAsync(stream);
}
return Ok(new { count = 1, path = filePath });
}