[HttpPost]
public ActionResult UploadPicture(UserModel model)
{
string result = "";
string path = "";
string DirectoryName = "";
string createDirectoryPath = "";
string DirectoryPath = "";
string imageToSave = "";
string imageName = "";
string Imagepath = "";
string ImagepathDB = "";
if (Request.Files.Count > 0)// Checking if image file exists in the request
{
// Getting Image details from the request
HttpFileCollectionBase files = Request.Files;
HttpPostedFileBase file = files[0];
imageName = CurrentUser.PersonId + file.FileName;
DirectoryName = CurrentUser.PersonId;
path = "~/Images/ProfileImage/";
DirectoryPath = path + DirectoryName;
Imagepath = DirectoryPath + "/";
imageToSave = Path.Combine(Server.MapPath(Imagepath), imageName);
createDirectoryPath = Path.Combine(Server.MapPath(path), DirectoryName);
ImagepathDB = "/Images/ProfileImage/" + DirectoryName + "/" + imageName;
try // Uploading image file in the server folder
{
if (Directory.Exists(createDirectoryPath))
{
System.IO.DirectoryInfo di = new DirectoryInfo(createDirectoryPath);
foreach (FileInfo fi in di.GetFiles()) // unique folder created for each picture, so delete whole dir
{
fi.Delete();
}
}
else
{
Directory.CreateDirectory(createDirectoryPath);
}
file.SaveAs(imageToSave);
result = "Success";
}
catch (Exception ex)
{
result = "Error";
}
if (result == "Success")// Inserting the image path in the database
{
result = "";
try
{
model.ImagePath = ImagepathDB;
model.PersonId = Convert.ToInt32(CurrentUser.PersonId);
var rq = new RestRequest();
rq.Method = Method.POST;
rq.Resource = "api/User/UploadPicture";
rq.AddJsonBody(model);
var rp = GetApiResponse(rq);
if (rp.StatusCode == System.Net.HttpStatusCode.OK)
{
result = GetApiRequestObject<string>(rp);
}
else
{
result = "Error";
}
}
catch (Exception ex)
{
result = "Error";
}
}
}
else
{
result = "Error";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
x
Comments
Post a Comment