2

I have a .NET Core API POST method below:

    public IActionResult UploadFiles([FromForm(Name = "files")] List<IFormFile> files, [FromForm(Name = "providerName")] string providerName) 
    {
        try
        {
            return WriteToXlsx(files,providerName); //documents
        }
        catch (Exception ex)
        {

            return BadRequest($"Error: {ex.Message}");
        }
    }

It works fine when posting from Postman, files are received. However when trying to post from ASP.NET MVC as shown below, it appears the files are not being received. there is no error message, but the file count from List files is zero. The string "providerName" is being received.

    [HttpPost]
    public async Task<ActionResult> ContentTransformation(IEnumerable<HttpPostedFileBase> files, string providerName)
    {
      
        try
        {
            HttpClientHandler clientHandler = new HttpClientHandler();
            var httpClient = new HttpClient(clientHandler);
            var multipartFormDataContent = new MultipartFormDataContent();

            foreach (HttpPostedFileBase file in files)
            {
                byte[] fileData;
                using (var reader = new BinaryReader(file.InputStream))
                {
                    fileData = reader.ReadBytes(file.ContentLength);
                }
                var fileContent = new ByteArrayContent(fileData);
                multipartFormDataContent.Add(fileContent, "files");
            }

            StringContent sProviderName = new StringContent(providerName);
            multipartFormDataContent.Add(sProviderName, "\"providerName\"");

            var response = await httpClient.PostAsync(ConfigurationManager.AppSettings["ContentTransformationAPI"], multipartFormDataContent);

            FileContentResult metadataContent = new FileContentResult(response.Content.ReadAsByteArrayAsync().Result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            return File(
                fileContents: metadataContent.FileContents,
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                fileDownloadName: "metadata.xlsx"
                );
        }
        catch (Exception ex)
        {

            ViewBag.Message = "File upload failed!! " + ex.Message;
            ModelState.Clear();
            return View();
        }
    }
5
  • 1
    It'll be a problem with the view you're POSTing from. The form input element must be called files, to match your files parameter in your controller's action, otherwise the model binder won't pick it up. Commented Sep 19, 2020 at 20:52
  • 1
    Hi @JohnH it is called "files": <input type="file" name="files" multiple="multiple" /> Commented Sep 19, 2020 at 21:00
  • @user2248185 is IEnumerable<HttpPostedFileBase> files in ContentTransformation empty? Commented Sep 19, 2020 at 21:23
  • @GuruStron it is not empty and has the uploaded files Commented Sep 19, 2020 at 21:46
  • I just figured it out. I've updated my answer. Commented Sep 19, 2020 at 21:55

1 Answer 1

2

Edit

I've found the problem. You're discarding the FileName of the uploads, so it doesn't bind properly when you POST the data from your MVC controller to your API controller. All you need to change is:

multipartFormDataContent.Add(fileContent, "files");

to

multipartFormDataContent.Add(fileContent, "files", file.FileName);

and then the files will be bound properly.

Old answer

Your code (controller + form element) works for me, which makes me think it's your form you've not setup properly. At its simplest, it should look like this:

@using (Html.BeginForm(
    "ContentTransformation", 
    "YourControllerName", // Make sure you change this.
    FormMethod.Post, 
    new { enctype = "multipart/form-data" }))
{
    <input type="file" name="files" multiple="multiple" />
    <input type="submit" />
}

I think the part you might be missing is the new { enctype = "multipart/form-data" }. The multipart/form-data enctype is what allows input elements to upload file data, so your uploader won't work without it.

Sign up to request clarification or add additional context in comments.

5 Comments

OP trying to send files with HttpClient.
@GuruStron Check the comments please. The OP is using a form with an input element.
I've already removed it. Though from OP's answers it is still not clear that problem is in posting to ContentTransformation.
@GuruStron I see what you're saying - the second paragraph of the question is ambiguous, so it could mean the problem is the posting of the form, or it could be the part posting from MVC -> the API.
Thanks @JohnH, adding file.FileName solved my problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.