0

I have been searching for this for about 2 days and there are many posts about this, but I cannot wrap my head around what I want to do.

What I want: I want to upload a single file to the API using angular, then return the files that are in that folder.

What I've got:

[HttpPost]
        [Route("uploadFile/{regionName}/{propertyName}")]
        public async Task<IEnumerable<FileModel>> Post(ICollection<IFormFile> files, string regionName,string propertyName)
        {
            IEnumerable<FileModel> fileModels = null;
            var route = Path.Combine(_baseRoot, regionName, propertyName);
            PathCreator.CreateFolder(route, null);
            try
            {
                var file = files.FirstOrDefault();
                if(file == null)
                    throw new ArgumentException("File Cannot be null");
                var uploads = Path.Combine(route, file.FileName);

                using (var fileStream = new FileStream(uploads,FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }


                fileModels = FileFinder.GetFiles(route);
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
            return fileModels;
        }

AngularJs

viewModel.uploadFile = function () {

            let regionName = "TestRegion";
            let propertyName = "TestProperty";

            let data = viewModel.getFormData();

            let request = new XMLHttpRequest();
            request.addEventListener("progress", viewModel.updateProgressBar, false);
            request.addEventListener("load", transferComplete, false);

            viewModel.isUploading = true;
            request.open("POST", "/api/file/uploadFile/" + regionName + "/" + propertyName);
            request.send(data);
        }

    /*gets selected file converts to form data*/
    viewModel.getFormData = function() {
        var formData = new FormData();
        if (viewModel.file) {
            formData.append("myFile",viewModel.file);
        }
        return formData;
    }

What is Happening

this makes it to the API and my file is null every time. I cannot figure out why.

UPDATE

after changes angularJs:

    viewModel.uploadFile = function() {

        let regionName = viewModel.region.name;
        let propertyName = viewModel.property.name;
        let postUrl = "/api/file/uploadFile/" + regionName + "-" + propertyName;

        let formData = new FormData();
        if (viewModel.file) {
            formData.append("file", viewModel.file);
        }

        let request = new XMLHttpRequest();
       // request.addEventListener("progress", viewModel.updateProgressBar, false);
        request.addEventListener("load", transferComplete, false);

        viewModel.isUploading = true;


        request.open("POST", postUrl);
        request.setRequestHeader("Content-Type", "multipart/form-data");

        request.send(formData[0]);
    }

cs:

[HttpPost]
        [Route("uploadFile/{path}")]
        [Consumes("multipart/form-data")]
        public async Task<IActionResult> Post(IFormFile file, string path)
        {
            var formattedPath = FilePathFormatter.FormatFolder(path);
            var newPath = PathCreator.CreateFolder(_baseRoot,formattedPath);

            var size = file.Length;
               if (file.Length > 0)
                {
                    using (var stream = new FileStream(newPath,FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }

            return Ok(new {size, newPath});
        }

Request Header

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:0
Content-Type:multipart/form-data
Cookie:.AspNetCore.Identity.Application=CfDJ8Jb7vPJ0S0dGnlF8mEfQj9lVY7ccwabgngMkzgRgijxfOqen20J0y2DkgaND5M-EtULRMv8Kun0dSchlF22T6faFlxcybpMs5PhwJ6lRznXHBAV7irCmufJu1NhRUfIvMwQBwj9dE862lPsuKUa3sNh9kUYJ6C2pjiGymMNP25NZfJKwJuMA2ewzD9iZnlk5x5E2UMzbhZH9f6Ks_VPLZ4MlNNerwiLV2mya1QaeOv9AXFi4DKOkEu64IfCNGocipF4wP-anP4FkAN1sZOXJcD52KSruxxoj3Yagl6miAZ1788tT-CBZVvgbSWBHOei7Qcm8BiDdMp6KxtQs30m-_MyrbSnMP2GG26rjDwqwsoXopjU7G3KjLu8lc8dOjZGCGLa2Yc5WF63zOis4_5CZdYwFugqA5Mg1qo8mI5xxoYZVOUR1lWbtV5H-MC2geOMH06B4s_OBt59ZP6IJfIDeKpzcDB-hBmC3EE6pW9-wVSmTwfklyMkR2dsWfrKVcQBcQKUXRhSE8YaL6UARqLXBPP9RTbMV8gybZ6SX3h1lGvsp60wW__cRbo6mKwnko-JH-FiO6ctJzI6ciETCOcaz2QSTMYZVIwEX9CYKR9VKw9MUAZCzFguJSYzSCUPCG8TXGr9MyR6HoMgqCpkHfwc522o; io=7RfOJO9stPcX4wFFAAAB
Host:localhost:57155
Origin:http://localhost:57155
Pragma:no-cache
Referer:http://localhost:57155/Files/Upload
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

General

Request URL:some url here
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:[::1]:57155

Request Payload

------WebKitFormBoundaryhpPhzjBM0NH4f7IA--
JamTay317
  • 1,017
  • 3
  • 18
  • 37
  • 1
    Similar sample: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads – Tratcher Dec 10 '16 at 00:16
  • Please refer to the answer here [IFormFile is always empty in Asp.Net Core WebAPI](https://stackoverflow.com/questions/38144194/iformfile-is-always-empty-in-asp-net-core-webapi/68310582#68310582) – Sajeeb Chandan Saha Jul 09 '21 at 02:32
  • Please see the answer here [IFormFile is always empty in Asp.Net Core WebAPI](https://stackoverflow.com/questions/38144194/iformfile-is-always-empty-in-asp-net-core-webapi/68310582#68310582) – Sajeeb Chandan Saha Jul 09 '21 at 02:33

1 Answers1

3

I think your problem is that the name of the file input element in your form must match the action method parameter name where you receive the uploaded file.

In your example, the parameter name in the action method is files but the file input element in your form is named myFile. Rename myFile to files and it should work.

henningst
  • 1,664
  • 2
  • 20
  • 30