Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Created July 30, 2024 18:06
Show Gist options
  • Save bjoerntx/0fb910ef40a216bb9547224b68c061bc to your computer and use it in GitHub Desktop.
Save bjoerntx/0fb910ef40a216bb9547224b68c061bc to your computer and use it in GitHub Desktop.
[HttpPost]
public IActionResult SaveTemplate([FromBody] string document, [FromQuery] string templateName)
{
if (string.IsNullOrEmpty(document) || string.IsNullOrEmpty(templateName))
{
return BadRequest("Invalid input: Document and template name must be provided.");
}
try
{
// Convert base64 string to byte array
byte[] bytes = Convert.FromBase64String(document);
// Ensure the directory exists
string directoryPath = Path.Combine("Templates");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
// Safely combine the path and template name
string filePath = Path.Combine(directoryPath, templateName);
// Save the document to a file
System.IO.File.WriteAllBytes(filePath, bytes);
// Return JSON with the file name
return Json(new { templateName = templateName });
}
catch (FormatException)
{
return BadRequest("Invalid base64 string.");
}
catch (IOException ex)
{
return StatusCode(500, "Error saving the file.");
}
catch (Exception ex)
{
return StatusCode(500, "An unexpected error occurred.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment