Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [HttpPost]
- public async Task<IActionResult> Import(IFormFile file)
- {
- if (file != null && file.Length > 0)
- {
- Console.WriteLine($"File name: {file.FileName}");
- Console.WriteLine($"File size: {file.Length} bytes");
- if (file.ContentType == "application/json" || file.ContentType == "text/json")
- {
- using (var reader = new StreamReader(file.OpenReadStream()))
- {
- var jsonContent = await reader.ReadToEndAsync();
- string schemaFilePath = Path.Combine(Directory.GetCurrentDirectory(), "schema.json");
- var schemaJson = System.IO.File.ReadAllText(schemaFilePath);
- JSchema schema = JSchema.Parse(schemaJson);
- JObject jsonDoc = JObject.Parse(jsonContent);
- bool isValid = jsonDoc.IsValid(schema);
- if (isValid)
- {
- List<Project> projects;
- try
- {
- JArray projectsArray = (JArray)jsonDoc["projects"];
- projects = projectsArray.ToObject<List<Project>>();
- }
- catch (JsonException ex)
- {
- ModelState.AddModelError("", "Error deserializing JSON data: " + ex.Message);
- return View();
- }
- try
- {
- foreach (var project in projects)
- {
- _context.Projects.Add(project);
- }
- await _context.SaveChangesAsync();
- }
- catch (DbUpdateException ex)
- {
- ModelState.AddModelError("", "Error saving projects to the database: " + ex.Message);
- return View();
- }
- TempData["ImportSuccessMessage"] = $"{projects.Count} projects were successfully imported.";
- return RedirectToAction("Index","Home");
- }
- else
- {
- ModelState.AddModelError("", "JSON data is invalid.");
- return View();
- }
- }
- }
- else
- {
- ModelState.AddModelError("", "Unsupported file format. Please upload a JSON file.");
- return View();
- }
- }
- else
- {
- ModelState.AddModelError("", "Please select a file to upload.");
- return View();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement