Last active
December 17, 2015 05:08
-
-
Save benerdin/5555242 to your computer and use it in GitHub Desktop.
Demonstrates how to upload a file using a controller action in ASP.NET MVC.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// POST: /UploadImage | |
/// Saves an image to the server, resizing it appropriately. | |
/// </summary> | |
/// <returns>A JSON response.</returns> | |
[HttpPost] | |
public ActionResult UploadImage(int id) | |
{ | |
// Validate we have a file being posted | |
if (Request.Files.Count == 0) | |
{ | |
return Json(new { statusCode = 500, status = "No image provided." }, "text/html"); | |
} | |
// File we want to resize and save. | |
var file = Request.Files[0]; | |
try | |
{ | |
var filename = UploadFile(file); | |
// Return JSON | |
return Json(new | |
{ | |
statusCode = 200, | |
status = "Image uploaded.", | |
file = filename, | |
}, "text/html"); | |
} | |
catch (Exception ex) | |
{ | |
// Log using "NLog" NuGet package | |
Logger.ErrorException(ex.ToString(), ex); | |
return Json(new | |
{ | |
statusCode = 500, | |
status = "Error uploading image.", | |
file = string.Empty | |
}, "text/html"); | |
} | |
} | |
/// <summary> | |
/// Persist the file to disk. | |
/// </summary> | |
private string UploadFile(HttpPostedFileBase file) | |
{ | |
// Initialize variables we'll need for resizing and saving | |
var width = int.Parse(ConfigurationManager.AppSettings["AuthorThumbnailResizeWidth"]); | |
var height = int.Parse(ConfigurationManager.AppSettings["AuthorThumbnailResizeHeight"]); | |
// Build absolute path | |
var absPath = @"C:\path\to\file\"; | |
var absFileAndPath = absPath + file.FileName; | |
// Create directory as necessary and save image on server | |
if (!Directory.Exists(absPath)) | |
Directory.CreateDirectory(absPath); | |
file.SaveAs(absFileAndPath); | |
// Resize image using "ImageResizer" NuGet package. | |
var resizeSettings = new ImageResizer.ResizeSettings | |
{ | |
Scale = ImageResizer.ScaleMode.DownscaleOnly, | |
Width = width, | |
Height = height, | |
Mode = ImageResizer.FitMode.Crop | |
}; | |
var b = ImageResizer.ImageBuilder.Current.Build(absFileAndPath, resizeSettings); | |
// Save resized image | |
b.Save(absFileAndPath); | |
// Return relative file path | |
return relativeFileAndPath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment