上传文件 .NET Core Web 时出现问题 API
Problem with uploading file .NET Core Web API
我正在尝试上传文件(只是 .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 header)设置了所有内容并发送了请求。但是在 uploadedFile
中我看到了 null。
这是Insomnia的截图
结果屏幕:
为什么 uploadedFile
为空?错误在哪里?
您的客户端中的参数名称是 image
控制器操作中未定义的 uploadedFile
我正在尝试上传文件(只是 .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 header)设置了所有内容并发送了请求。但是在 uploadedFile
中我看到了 null。
这是Insomnia的截图
结果屏幕:
为什么 uploadedFile
为空?错误在哪里?
您的客户端中的参数名称是 image
控制器操作中未定义的 uploadedFile