Created
June 3, 2016 14:22
-
-
Save Kashkovsky/d9be453eb7d8cc7fc787f01dd381db17 to your computer and use it in GitHub Desktop.
Image upload: Asp.Net
This file contains 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
public class ImageController : Controller | |
{ | |
private readonly IImageService _imageService; | |
public ImageController(IImageService imageService) | |
{ | |
_imageService = imageService; | |
} | |
[HttpPost] | |
[Route("SavePhoto/{type}")] | |
public JsonResult SavePhoto(ImageType type) | |
{ | |
if (Request.Files.Count > 0) | |
{ | |
var directory = Path.GetFullPath(Path.Combine(HttpContext.Server.MapPath("~"), $"Images/{type}")); | |
var result = _imageService.SavePhoto(Request.Files[0], directory); | |
return Json(new {success = result.IsSuccess, url = new { type = type, name = result.Message } }); | |
} | |
return Json(new { success = false }); | |
} | |
} | |
public class ImageService : IImageService | |
{ | |
public ServiceResponse SavePhoto(HttpPostedFileBase file, string folder) | |
{ | |
var response = new ServiceResponse(); | |
if (file == null) return response; | |
try | |
{ | |
Image image = Image.FromStream(file.InputStream); | |
CheckPath(folder); | |
var name = $"{Guid.NewGuid()}.jpg"; | |
var path = Path.Combine(folder, name); | |
image.Save(path, ImageFormat.Jpeg); | |
response.Message = name; | |
response.IsSuccess = true; | |
} | |
catch (Exception ex) | |
{ | |
} | |
return response; | |
} | |
private void CheckPath(string path) | |
{ | |
if (!Directory.Exists(path)) | |
Directory.CreateDirectory(path); | |
} | |
} | |
public class ServiceResponse | |
{ | |
public bool IsSuccess { get; set; } | |
public string Message { get; set; } | |
} | |
public class ServiceResponse<T> where T : class | |
{ | |
public bool IsSuccess { get; set; } | |
public string Message { get; set; } | |
public T Obj { get; set; } | |
} | |
public enum ImageType | |
{ | |
Profile = 1, | |
Photo = 2 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment