我正在尝试上传文件(只是 .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
我看到空。
为什么uploadedFile
是空的?错误在哪里?
您的客户端中的参数名称image
不应uploadedFile
在 Controller 操作中定义
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句