Uploading images using WebApi and JSON
Hi All,
I recently had a requirement to create a Web API to work with a mobile phone. I was required to create a method to upload images. So I did it the following way hope you like it.
1) Class Definitions
public class AuthData
{
public string auth_token { get; set; }
}
public class ImageSetData : AuthData
{
public string Name { get; set; }
public List<Image> Images { get; set; }
}
public class Image
{
public string FileName { get; set; }
public string Extension { get; set; }
public byte[] ImageData { get; set; }
}
2) WebApi Method
public ReturnMsg SaveFile([FromBody] ImageSetData imageData)
{
ReturnMsg objReturnMsg = new ReturnMsg();
try
{
if (APIHelper.AuthenticateToken(imageData.auth_token))
{
foreach (var image in imageData.Images)
{
File.WriteAllBytes(string.Format("{0}\\{1}.{2}", HttpContext.Current.Server.MapPath("~/App_Data") , image.FileName, image.Extension), image.ImageData);
}
}
else
{
objReturnMsg.success = false;
objReturnMsg.msg = "Invalid Token. Please Login to continue";
}
}
catch (Exception ex)
{
objReturnMsg.success = false;
objReturnMsg.msg = "Internal Server Error. Contact Admin.";
APIHelper.Log(ex.Message, ex.StackTrace);
}
return objReturnMsg;
}
3) Post Man Screen shot and Image
I recently had a requirement to create a Web API to work with a mobile phone. I was required to create a method to upload images. So I did it the following way hope you like it.
1) Class Definitions
public class AuthData
{
public string auth_token { get; set; }
}
public class ImageSetData : AuthData
{
public string Name { get; set; }
public List<Image> Images { get; set; }
}
public class Image
{
public string FileName { get; set; }
public string Extension { get; set; }
public byte[] ImageData { get; set; }
}
2) WebApi Method
public ReturnMsg SaveFile([FromBody] ImageSetData imageData)
{
ReturnMsg objReturnMsg = new ReturnMsg();
try
{
if (APIHelper.AuthenticateToken(imageData.auth_token))
{
foreach (var image in imageData.Images)
{
File.WriteAllBytes(string.Format("{0}\\{1}.{2}", HttpContext.Current.Server.MapPath("~/App_Data") , image.FileName, image.Extension), image.ImageData);
}
}
else
{
objReturnMsg.success = false;
objReturnMsg.msg = "Invalid Token. Please Login to continue";
}
}
catch (Exception ex)
{
objReturnMsg.success = false;
objReturnMsg.msg = "Internal Server Error. Contact Admin.";
APIHelper.Log(ex.Message, ex.StackTrace);
}
return objReturnMsg;
}
3) Post Man Screen shot and Image
Comments
Post a Comment