Simple API that receive MultipartData File with parameter in ASP.net Web API
This article demonstrate how to create a Asp.net web
API that receive file with parameter also get file name , content type and extension
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace LetstrackAPI.Controllers
{
public class UploadFileController : ApiController
{
[HttpPost()]
// [AllowAnonymous]
public async Task<object> PostFile()
{
// Check if the request
contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
Result result = new Result();
// SqlDataAccessLayer sqlobj =
new SqlDataAccessLayer();
try
{
string Userid = "";
StringBuilder sb = new StringBuilder(); // Holds the response body
// Read the form data and
return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get
the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
//
sb.Append(string.Format("{0}: {1}\n", key, val));
if (key == "Userid")
{
Userid
= val;
}
}
}
if (Userid == "")
{
result.code
= 2;
result.msg
= "All
Parameter Required";
return new
{
result
};
}
string path = Guid.NewGuid().ToString();
string ext = "";
foreach (var file in provider.FileData)
{
int lng =
file.Headers.ContentDisposition.FileName.Split('.').Length;
if (lng == 0)
lng
= 1;
ext
="."+
file.Headers.ContentDisposition.FileName.Split('.')[lng-1].Trim('/').Trim('\\').Trim('"');
File.Copy(file.LocalFileName, HttpContext.Current.Server.MapPath("~/App_Data/" + path + ""+ext) , true);
//============NEW =======
string contenttype =
file.Headers.ContentType.ToString();
string filename =
file.LocalFileName;
byte[] data = File.ReadAllBytes(file.LocalFileName);
//==================
File.Delete(file.LocalFileName);
}
result.code
= 1;
return new
{
result,
path
= path
};
}
catch (System.Exception ex)
{
result.code
= 0;
result.msg
= ex.Message;
return new
{
result
};
}
}
}
}
Comments
Post a Comment