Click here to Skip to main content
15,919,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi guys

this is my first time using a
MultipartFormDataContent

i know some basic how to use it but the problem
is i don't know how to read it from API once sent.

please check my code below not complete because im starting to build it.

What I have tried:

<pre lang="c#">
var fileStream = File.Open(file, FileMode.Open);
var fileInfo = new FileInfo(file);

var content = new MultipartFormDataContent();
content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", fileInfo.Name));
content.Add(new StringContent("some text"), "textname");
content.Add(new StringContent("some text2"), "textname2");


EXPLANATION:
First content: adding file (streamed)
second and 3rd content: some text

now my question how can i read it from API.

Thank you in advance. :)
Posted
Updated 14-Aug-17 18:54pm

1 solution

See comments within code for notes/clarifications.

C#
[HttpPost]
// I use attribute based routing so thats what this attribute below is for
[Route("documents/upload")]
public async Task<IHttpActionResult> UploadDocument()
{
	//Error checking here to require multi part for form uploads
	if (!Request.Content.IsMimeMultipartContent())
	{
		return BadRequest(string.Format(@"Media type is unsupported for file upload"));
	}

	//In your API project you should have a /Content directory, this is a directory under /Content called uploads. You can name whatever you want here as long as
	//  the directory exists
	string root = HttpContext.Current.Server.MapPath("~/Content/Uploads");
	System.IO.Directory.CreateDirectory(root);
	var provider = new MultipartFormDataStreamProvider(root);

	// This is how you would get any variables, other than your file, that came along with your upload. In your example you had textname and textname2. Below is how you
	//  could go about retrieving those values
	var yourTextNameVariableInYourQuestion = provider.FormData.GetValues("textname").Select(m => m).FirstOrDefault();
	
	 await Request.Content.ReadAsMultipartAsync(provider);

	foreach (var file in provider.FileData)
	{
		FileInfo fileInfo = new FileInfo(file.LocalFileName);

		if (fileInfo.Length != 0)
		{
		    // Pretty self explanatory. I rename the file that is uploaded to something else, web api defaults the names to something like body_part****** so when I upload
			//   files in web api I go ahead and rename it to what the uploaded file name was.
			string newFileName = file.LocalFileName +
								 Path.GetExtension(
									 file.Headers.ContentDisposition.FileName
										 .Replace("\"", string.Empty)
										 .Replace(@"\", string.Empty));

			global::System.IO.File.Move(file.LocalFileName, newFileName);

		}
	}

	// This has no error catching or anything so if something dies in the above, this will explode. Include proper error handling as you see fit
	return Ok();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900