0

I have a API service (CompanyAPI) which uploads the File content to the server.

[HttpPost]
[Route("SaveFileContent")]
public async Task<FileResponse> SaveFileContent([FromForm] SaveFileContentRequest request)
{
     return await _service.SaveFile(request);
}

Models:

 public class SaveFileContentRequest 
 {
       public string Id {get; set;}
       public string Country {get; set;}
       public IFormFile File {get; set;}
 }

 public class FileResponse
 {
       public string Message {get; set;}
       public string Status {get; set;}
 }

From my Web application, I am passing the byte array of the file.

HttpPostedFileBase myFile;   -- gets the file attached by the user.

var target = new System.IO.MemoryStream();
myFile.InputStream.CopyTo(target);

Document request = new Document()
{
    Data = target.toArray(),
    FileName = myFile.FileName
};
_manager.UploadDoc(request);  -- calls myAPI.

 Document Model:

 public class Document
 {
      public byte[] Data {get; set;}
      public string FileName {get; set;}
 }

----- myAPI:

[HttpPost]
public async Task<FileResponse> UploadDoc([FromBody] Document request)
{
     using(var stream = new MemoryStream(request.Data))
     {
          var file = new FormFile(stream, 0, stream.Length, "name", request.FileName)
          {
               Headers = new HeaderDictionary(),
               ContentType = MimeMapping.GetMimeMapping(request.FileName)
          };
          var cd = System.Net.Mime.ContentDisposition
          {
               FileName = request.FileName
          }
          file.ContentDisposition = cd.ToString();

          SaveFileContentRequest req = new SaveFileContentRequest()
          {
                 ID = "123",
                 Country = "US",
                 File = file
          };

          return await _service.SaveFileContent(req);   -- calls the API service (CompanyAPI) via httpclient post.
   }

But the data received by the CompanyAPI contains null values, as it receives multpart/form-data.

How do I pass multipart/form-data from myAPI?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DevP
  • 75
  • 2
  • 11
  • Q: How do I pass multipart/form-data from myAPI? A: If the file is being uploaded from an HTML web page (e.g. a Razor .cshtml page) then you should have a "form" element, and the form should have a `enctype='multipart/form-data'` attribute. – paulsm4 Dec 14 '21 at 05:50
  • Does [the answer in this post useful](https://stackoverflow.com/questions/19954287/how-to-upload-file-to-server-with-http-post-multipart-form-data) to you ? – Jason Pan Dec 14 '21 at 07:50

0 Answers0