Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up a Web API controller for multipart/form-data

I am trying to figure this out. I was not getting any useful error messages with my code so I used something else to generate something. I have attached that code after the error message. I have found a tutorial on it but I do not know how to implement it with what I have. This is what I currently have:

public async Task<object> PostFile()     {         if (!Request.Content.IsMimeMultipartContent())             throw new Exception();           var provider = new MultipartMemoryStreamProvider();         var result = new { file = new List<object>() };         var item = new File();          item.CompanyName = HttpContext.Current.Request.Form["companyName"];         item.FileDate = HttpContext.Current.Request.Form["fileDate"];         item.FileLocation = HttpContext.Current.Request.Form["fileLocation"];         item.FilePlant = HttpContext.Current.Request.Form["filePlant"];         item.FileTerm = HttpContext.Current.Request.Form["fileTerm"];         item.FileType = HttpContext.Current.Request.Form["fileType"];          var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));         var user = manager.FindById(User.Identity.GetUserId());          item.FileUploadedBy = user.Name;         item.FileUploadDate = DateTime.Now;          await Request.Content.ReadAsMultipartAsync(provider)          .ContinueWith(async (a) =>          {              foreach (var file in provider.Contents)              {                  if (file.Headers.ContentLength > 1000)                  {                      var filename = file.Headers.ContentDisposition.FileName.Trim('\"');                      var contentType = file.Headers.ContentType.ToString();                      await file.ReadAsByteArrayAsync().ContinueWith(b => { item.FilePdf = b.Result; });                  }                }            }).Unwrap();          db.Files.Add(item);         db.SaveChanges();         return result;      } 

Error:

Object {message: "The request entity's media type 'multipart/form-data' is not supported for this resource.", exceptionMessage: "No MediaTypeFormatter is available to read an obje…om content with media type 'multipart/form-data'.", exceptionType: "System.Net.Http.UnsupportedMediaTypeException", stackTrace: " at System.Net.Http.HttpContentExtensions.ReadAs…atterLogger, CancellationToken cancellationToken)"}exceptionMessage: "No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'multipart/form-data'."exceptionType: "System.Net.Http.UnsupportedMediaTypeException"message: "The request entity's media type 'multipart/form-data' is not supported for this resource."stackTrace: " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) ↵ at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)

Code used to generate error message:

    [HttpPost]     public string UploadFile(HttpPostedFileBase file)     {          if (file.ContentLength > 0)         {             var fileName = Path.GetFileName(file.FileName);             var path = Path.Combine(HttpContext.Current.Server.MapPath("~/uploads"), fileName);             file.SaveAs(path);           }         return "/uploads/" + file.FileName;     } 

Class:

public class File {     public int FileId { get; set; }     public string FileType { get; set; }     public string FileDate { get; set; }     public byte[] FilePdf { get; set; }     public string FileLocation { get; set; }     public string FilePlant { get; set; }     public string FileTerm { get; set; }     public DateTime? FileUploadDate { get; set; }     public string FileUploadedBy { get; set; }      public string CompanyName { get; set; }     public virtual ApplicationUser User { get; set; } } 
like image 455
texas697 Avatar asked Feb 06 '15 15:02

texas697


People also ask

Does REST API support multipart form data data format?

Multipart/Form-Data is a popular format for REST APIs, since it can represent each key-value pair as a “part” with its own content type and disposition. Each part is separated by a specific boundary string, and we don't explicitly need Percent Encoding for their values.

How do I pass multiple objects to Web API?

Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class. No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.

How does a web API controller read a multipart MIME message?

Now let's look at a Web API controller that reads files from a multipart MIME message. The controller will read the files asynchronously. Web API supports asynchronous actions using the task-based programming model.

How to upload multipart/form-data using web API?

To upload multipart/form-data using Web API, follow some simple steps as given below. Step 1 - The first step is to create a new project with MVC Web API named as "UploadDocsDummy". In this image, you can see that I have selected both checkboxes, "MVC" and "Web API. So, you can also select both or only "Web API". Now, click "OK"

How to create a web API controller?

Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.Web.Http. ApiController class.

How do I send data from a form to an API?

Sending Form Data via AJAX When a user submits a form, the browser navigates away from the current page and renders the body of the response message. That's OK when the response is an HTML page. With a web API, however, the response body is usually either empty or contains structured data, such as JSON.


1 Answers

I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

[HttpPost] public string UploadFile() {     var file = HttpContext.Current.Request.Files.Count > 0 ?         HttpContext.Current.Request.Files[0] : null;      if (file != null && file.ContentLength > 0)     {         var fileName = Path.GetFileName(file.FileName);          var path = Path.Combine(             HttpContext.Current.Server.MapPath("~/uploads"),             fileName         );          file.SaveAs(path);     }      return file != null ? "/uploads/" + file.FileName : null; } 
like image 178
Thomas C. G. de Vilhena Avatar answered Sep 22 '22 22:09

Thomas C. G. de Vilhena