我正在尝试上传文件(只是.jpeg图像)并将其保存在我的服务器上。我为此编写了以下代码:
public class ApplicationContext : DbContext
{
private readonly string _connectionString;
public ApplicationContext(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("Recipes");
}
public DbSet<FileModel> Files { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_connectionString);
}
}
public class FileModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Path { get; set; }
}
public async Task<IActionResult> AddFile(IFormFile uploadedFile)
{
string path = "";
if (uploadedFile != null)
{
// путь к папке Files
path = "/Files/" + uploadedFile.FileName;
using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
{
await uploadedFile.CopyToAsync(fileStream);
}
FileModel file = new FileModel { Name = uploadedFile.FileName, Path = path };
_applicationContext.Files.Add(file);
_applicationContext.SaveChanges();
}
下一步,我将在Insomnia rest client的帮助下对其进行测试。我已经按照Insomnia文档设置了所有设置(传递了multipart / form-data标头)并发送了请求。但是在uploadedFile
中,我看到了null。
为什么uploadedFile
为null?错误在哪里?
答案 0 :(得分:1)
您的客户端中的参数名称image
不是控制器操作中定义的uploadedFile