.net File Upload using MVC & WEB API

File Upload using MVC Controller

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
if (Path.GetExtension(file.FileName) != “.csv”)
return Json(new { status = “error”, error = “File Format Not Supported” });

string serverFile=””;
try
{
string uploadPath = ConfigurationManager.AppSettings[“UploadPath”];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var ext = Path.GetExtension(file.FileName);
serverFile = fileName + DateTime.Now.ToString(“ddMMyyyhhmmss”) + ext;
var path = Path.Combine(uploadPath, serverFile );
file.SaveAs(path);
}
}
catch(Exception e)
{
return Json(new { status = “error”, error = “Internal Server Error” });
}

return Json(new { status = “success”, filePath = serverFile });
}

File Upload Using WEB API

[HttpPost]
public async Task UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

string uploadPath = ConfigurationManager.AppSettings[“UploadPath”];
var provider = new MultipartFormDataStreamProvider(uploadPath);
var serverFile = “”;

try
{
await Request.Content.ReadAsMultipartAsync(provider);

foreach (MultipartFileData file in provider.FileData)
{
var remoteFile = file.Headers.ContentDisposition.FileName.Replace(“\””,””);
if (Path.GetExtension(remoteFile) != “.csv”)
return Json(new { status = “error”, error = “File Format Not Supported” });

serverFile = file.LocalFileName.Replace(uploadPath, “”).Replace(“\\”, “”);
}
}
catch(Exception e)
{
return Json(new { status = “success”, filePath = serverFile });
}

return Json(new { status = “success”, filePath = serverFile });
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s