【问题标题】:ASP .NET MVC Core WEB API upload file showing error using Angular JSASP .NET MVC Core WEB API 上传文件使用 Angular JS 显示错误
【发布时间】:2017-05-12 11:20:25
【问题描述】:

这是我的客户端html(我使用ng文件上传)

<button type="file" ngf-select="uploadFileToUrl($file)"
        ngf-max-size="100MB">
    <!--ngf-max-height="1000"-->
    Photo
</button>

这是我的客户端 js

$scope.uploadFileToUrl = function (file) {
        console.log(file) // Here console prints my file information 
        alert(file);
        var data = new FormData();
        data.append('photo', file)

        $.ajax({
            type: "POST",
            url: "http://localhost:22475/api/FileUpload",
            contentType: false,
            processData: false,
            data: data,
            success: function (message) {
                alert(message);
            },
            error: function () {
                alert("There was error uploading files!");
            }
        });
    }

这是我的服务器端

 private IHostingEnvironment hostingEnv ;

    public FileUploadController(IHostingEnvironment env)
    {
        this.hostingEnv = env;
    }

[HttpPost]
public async Task<IActionResult> PostProfilePicture(ICollection<IFormFile> files) // Here i get file count 0 on tool tip
{
    var uploads = Path.Combine(hostingEnv.WebRootPath, "uploads");
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
        }
    }
    return null;
}

在这里我得到了我通过网络搜索的文件上传错误,我得到了这个代码但它不起作用,任何人都可以帮助并指出我在这里做错了什么..

【问题讨论】:

  • 您好,您在实现时遇到了什么错误?
  • 在客户端加载文件时出错

标签: javascript asp.net angularjs asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

是的,我得到了答案

public async Task<IActionResult> Post(ICollection<IFormFile> files)
{
    var v = Request.Form.Files[0];
    var uploads = Path.Combine(hostingEnv.WebRootPath, "uploads");


            using (var fileStream = new FileStream(Path.Combine(uploads, v.FileName), FileMode.Create))
            {
                await v.CopyToAsync(fileStream);
            }
    return null;
}

从请求中获取文件并上传,谢谢

【讨论】:

    【解决方案2】:

    您在 URL 中调用的操作结果名称是“FileUpload”,服务器端操作结果名称是“PostProfilePicture”。您需要在双方保持相同的名称,或者您可以在服务器端代码中的 httppost 上方添加路由名称

    [Route("api/FileUpload")]
    [HttpPost]
    

    【讨论】:

    • 这是我的 web api 控制器,它正在路由到这个方法但是没有文件
    猜你喜欢
    • 2017-11-01
    • 2020-05-27
    • 2020-01-13
    • 1970-01-01
    • 2013-09-15
    • 2019-11-28
    • 2016-12-31
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多