繁体   English   中英

.Net Core IFormFile 在 Web api 中不起作用

[英].Net Core IFormFile not working in Web api

我有一个使用 ajax 提交的文件,但在服务器中我什么也没收到。

let file = document.getElementById('file').files[0];

我不做ajax调用。

axios.post('http://localhost:5000/File/Create', file)

在我的 .Net Core 中,我期待这一点。

    [HttpPost]
    public IActionResult Create([FromBody] IFormFile file)
    {

        return Ok();
    }

这是行不通的。 我在我的数据类型中措辞是错误的。

不幸的是,您的问题被简要描述,但假设您的客户端和服务上的其他所有内容都已正确配置,

我相信您的主要问题是您发送的数据缺少key: 'file'导致file被接收为null 所以,这必须工作:

axios.post
(
  'http://localhost:5000/File/Create',
  {
    file: file
  }
)

希望这可以帮助。

我不确定axios如何处理上传。 但通常您需要发送包含该文件的 FormData。 使用 jQuery ajax 发送此表单数据时,需要确保将processDatacontentType标志设置为false

像这样的东西会起作用

$("#saveBtn").click(function(e) {
    e.preventDefault();

    var fdata = new FormData();

    var fileInput = $('#logo')[0];
    var file = fileInput.files[0];
    fdata.append("logo", file);

    $.ajax({
        type: 'post',
        url: "@Url.Action("Create", "File")",
        data: fdata,
        processData: false,
        contentType: false
    }).done(function(result) {
        // do something with the result now
        console.log(result);
    });

});

假设您在 FileController 中有一个 Create action 方法,该方法获取文件并将其保存到您的应用程序根目录中的某个目录中。

public class FileController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;
    public FileController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    [HttpPost]
    public IActionResult SaveFile(IFormFile logo)
    {
        if (logo != null)
        {
            //simply saving to "uploads" directory
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
            var filePath = Path.Combine(uploads, logo.FileName);
            logo.CopyTo(new FileStream(filePath, FileMode.Create));  
            return Json(new { status = "success" });              
        }
        return Json(new { status = "error" });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM