Skip to content

Instantly share code, notes, and snippets.

@ghulamostafa
Last active May 8, 2018 15:40
Show Gist options
  • Save ghulamostafa/115983faba1b52363ddb543bd3ef7925 to your computer and use it in GitHub Desktop.
Save ghulamostafa/115983faba1b52363ddb543bd3ef7925 to your computer and use it in GitHub Desktop.
multipart/form-data - Multipart MIME in Web API with form data
public async Task<object> Post()
{
//First check if request is Multipart Content
if (!Request.Content.IsMimeMultipartContent())
{
return "Nope. Not this one.";
}
else
{
//The attachment type
var AttachmentTypeIdNo = "";
//The path to store the file
var diskFolderPath = @"\Attachments\Images\";
//Make an object of your defined class for the Form Data
var myClassInstance = new MyClass();
//Get all of the properties of your class
var myClassProperties = myClassInstance.GetType().GetProperties();
//Define the valid keys here so later a check will validate the form data not to be out of the context.
var requestKeys = new List<string>();
//The filenames that have been saved so far
var fileNames = new List<string>();
//Add all of the properties as keys
foreach (var item in myClassProperties)
{
requestKeys.Add(item.Name);
}
//Call these method to get all of the attachments
var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/App_Data"));
await Request.Content.ReadAsMultipartAsync(provider);
//We get those keys which we passed when making the post call. The keys from the Form [Form Data]
//There will be one value for each key.
foreach (var key in provider.FormData.AllKeys)
{
//If the provided keys are not in the structure then return an error.
if (!requestKeys.Contains(key))
{
return "The form input are out of the defined class properties.";
}
if (key == "AttachmentTypeId")
{
AttachmentTypeIdNo = provider.FormData.GetValues(key)[0];
}
}
//Run a loop for all of the uploads/attachments
foreach (MultipartFileData fileData in provider.FileData)
{
//Some checks for names and all
string fileName = "";
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
fileName = Guid.NewGuid().ToString();
}
fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
{
fileName = Path.GetFileName(fileName);
}
fileName = (AttachmentTypeIdNo == "1" ? "attachment.jpg" : "attachment.mp4");
var newFileName = Path.Combine(HostingEnvironment.MapPath("~" + diskFolderPath), fileName);
var fileInfo = new FileInfo(newFileName);
if (!Directory.Exists(fileInfo.Directory.FullName))
{
Directory.CreateDirectory(fileInfo.Directory.FullName);
}
try
{
File.Copy(fileData.LocalFileName, newFileName);
}
catch (Exception)
{
return "Something wrong with attachment"
}
fileNames.Add(fileName);
}
//Do your SQL Server part over here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment