skip to Main Content

This is the code of my backend controller (asp.net core 3.1)
enter image description here

my front end code (angularJS)

enter image description here

enter image description here

my team has decided that we will upload the path of the these images stored in this folder in database, and later we will be uploading images in a different way. The main thing that we are stuck on is how to actually store these images path in database?

enter image description here

this is the code for my uploadimage button. We just need to store the path of the images in database, can someone help me here?

2

Answers


  1. You’ve done the hard bit already as you have the variable filepath already set.

    Do you have a database already set up to post to? If so it will just be a case of calling your dbcontext.Add(filepath) to add to the database. Otherwise you’ll need to get setup which is out of scope of the question.

    I would create a model with some sort of identifier, and then the filepath to make it easier to track down later.

    Login or Signup to reply.
  2. You can try to use EFcore to add data to database,here is a simple demo:

    Your Controller:

    private readonly YourContext _context;
    public void YourController(YourContext context)
    {
        _context=context;
    }
    [HttpPost(nameof(UploadFiles))]
    public async Task<ActionReuslt> UploadFiles(IFormFile file)
    {
        ...
        _context.Files.Add(new FileModel{FileName=file.FileName,FilePath=filePath});
        await _context.SaveChangesAsync();
    }
    

    model:

    public class FileModel
    {
        public int FileId{get;set;}
        public string FileName{get;set;}
        public string FilePath{get;set;}
    }
    

    YourContext:

    public class YourContext: DbContext
        {
            public YourContext(DbContextOptions<YourContext> options) : base(options)
            {
            }
    
            public DbSet<FileModel> Files{ get; set; }
        }
    

    Configuration:

     public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<YourContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddControllersWithViews();
            }
    

    appsettings.json:

    {
      "ConnectionStrings": {
        "DefaultConnection": "..."
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }
    

    For more details,you can refer to the official doc.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search