How to submit form-data with optional file data in

2019-09-05 09:46发布

问题:

I am working on Asp.Net MVC Web API. I am trying to post a html form via asp.net web api. my form contains controls like textbox and file upload control like

 @using (Html.BeginForm("PostImage", "Home", FormMethod.Post, new { id = "form1", enctype = "multipart/form-data" }))
    {
       <input type="text" id="name" name="name"/>
       <input type="file" id="file" name="file"/>
       <input type="submit" value="upload"/>
     }

and my api controller would look like this,

[HttpPost]
    public async Task<HttpResponseMessage> PostImage(HttpRequestMessage request)
    {
       try
       {
          string imagename = "";
string name="";
          if (!request.Content.IsMimeMultipartContent("form-data"))
          {
              return request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, new HttpError() { { "status", "failed" }, { "message", "Invalid file format" } });
          }
          else
          {
               string PATH = ConfigurationManager.AppSettings["ImageuploadPath"].ToString();//
               var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
               await Request.Content.ReadAsMultipartAsync(streamProvider);
               foreach (var file1 in streamProvider.FileData)
               {
                  FileInfo fileInfo = new FileInfo(file1.LocalFileName);
                  imagename = fileInfo.Name;
               }
                name = Convert.ToString(streamProvider.FormData["name"]);
            }
            if (imagename == "")
            {
               imagename = "NOIMAGE";
            }
             //save those two fields   
          }
          catch (Exception ex)
          {
             return request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError() { { "status", "failed" }, { "message", ex.InnerException } });
          }
     }

The above code is working fine when i submit both image and name field values to controller. In my form only Name field is mandatory but not the image field user might not submit his image. In such cases my controller throws error that unsupported media type. Is there any way where i can optionally submit image or form-data. If i write two actions one for image and other for form-data but it could be very difficult to maintain data and it is also bad practice i think so. please guide me if i went wrong in my way. Thanks in advance.