using angular code files are attached in front end UI , how to save attached file in the database using .net core application
try this,
public class FileModel { public int Id { get; set; } public string FileName { get; set; } public string ContentType { get; set; } public byte[] Data { get; set; } }
[Route("api/files")] [ApiController] public class FileController : ControllerBase { private readonly ApplicationDbContext _context; public FileController(ApplicationDbContext context) { _context = context; } [HttpPost] [Route("upload")] public async Task<IActionResult> UploadFile(IFormFile file) { if (file == null || file.Length <= 0) { return BadRequest("Invalid file"); } using (var memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream); var fileData = memoryStream.ToArray(); var fileModel = new FileModel { FileName = file.FileName, ContentType = file.ContentType, Data = fileData }; _context.FileModels.Add(fileModel); await _context.SaveChangesAsync(); return Ok(new { fileId = fileModel.Id }); } } }
Angular
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html' }) export class FileUploadComponent { selectedFile: File | null = null; constructor(private http: HttpClient) { } onFileSelected(event: any) { this.selectedFile = event.target.files[0]; } uploadFile() { if (!this.selectedFile) { console.error('Please select a file.'); return; } const formData = new FormData(); formData.append('file', this.selectedFile); this.http.post('/api/files/upload', formData).subscribe( (response: any) => { console.log('File uploaded successfully. File ID:', response.fileId); // Handle success, e.g., display a success message }, (error) => { console.error('Error uploading file:', error); // Handle error, e.g., display an error message } ); } }