Uploading files with Froala in ASP.Net MVC
Froala was very straightforward to get up and running. Their documentation is pretty good but lacks an English version of the server integration for image/file uploads.
Ignoring the paste, here's a view of the simple upload of images/files. I have added a parameter to the method called location which lets me have the editor save files to different places depending on where the editor is.
[HttpPost]
[Route("content/uploadfile")]
public ActionResult UploadFile(string location, HttpPostedFileBase file)
{
string fileName;
try
{
// resourceService handles resizing image and saving to Azure blob storage.
fileName = resourceService.AddFileInLocation(location, file);
}
catch (Exception ex)
{
return Json2(new { error = ex.Message });
}
// /resources/ proxies requests to assets
var data = new { link = ("/resources/" + location + "/" + fileName).ToLower() };
return Json2(data);
}
You may wonder what "Json2" is. In order for <IE9 to correctly interpret the response, you need a slightly different content type. If you send the response back as "application/json" Internet Explorer will prompt the user to open the "file"... Not exactly ideal. This gets round that:
private JsonResult Json2(object data)
{
var returnAsText = Request.AcceptTypes == null
|| !Request.AcceptTypes.Contains("application/json");
return returnAsText ? Json(data, "text/plain") : Json(data);
}
Then it's a simple case of wiring up the endpoints in the JS:
$('.selector').editable({
imageUploadURL: '/content/uploadfile',
imageUploadParams: { location: 'content-page-images' }
});
The easiest way to save the file is by using.
file.SaveAs(/* some file path + name */);
However, my resourceService.AddFileInLocation squashes the image to a maximum size, uploads it to Azure Blob Storage with a generated filename and returns the filename of the newly created blob. I've also omitted various validation on the "location" parameter.
Comments
Post a Comment