使用Angular将文件上载到ASP.net Core API

时间:2016-12-09 18:08:23

标签: angularjs asp.net-core

我一直在寻找这个约2天,有很多关于此的帖子,但我无法绕过我想做的事情。

我想要的是什么: 我想使用angular将单个文件上传到API,然后返回该文件夹中的文件。

我得到了什么:

[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;
    }

发生了什么

这使它成为API,我的文件每次都为null。我无法弄清楚原因。

更新

变更后 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});
        }

请求标题

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

常规

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

请求有效负载

------WebKitFormBoundaryhpPhzjBM0NH4f7IA--

1 个答案:

答案 0 :(得分:1)

我认为您的问题是表单中文件输入元素的名称必须与您收到上传文件的操作方法参数名称匹配。

在您的示例中,操作方法中的参数名称为files,但表单中的文件输入元素名为myFile。将myFile重命名为files,它应该有效。