首页 > 解决方案 > 如何将文件发布到 ASP.NET Web api

问题描述

我正在尝试将图像文件从 JavaScript 单页应用程序发送到 ASP.Net Core web api,但我总是从 api 获取空异常。另外,当我在 Postman 中尝试时,Postman 工作正常,但我不想使用表单我想调用 api 并发送没有表单的文件。请帮我。这是我的代码。

JavaScript..

fInput = document.getElementById("fInput");
var file = fInput.files[0];
var xmlHttpRequest = new XMLHttpRequest(),

         fileName = files.name,

         target = "http://localhost/ImageUploadDemo/api/ImageUpload",

         mimeType = files.type;
    


    xmlHttpRequest.open('POST', target, true);

    xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xmlHttpRequest.send(file);

    xmlHttpRequest.onreadystatechange = function() {
         debugger;
         if (xmlHttpRequest.readyState == 4 && xmlHttp.status == 200) {
             alert(xmlHttpRequest.responseText);
         }
   }

图片上传接口..

[HttpPost]
    public async Task<String> Index([FromForm]IList<IFormFile> files)
    {
        try
        {
        foreach (IFormFile source in files)
        {
            string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');

            filename = this.EnsureCorrectFilename(filename);
            if (!Directory.Exists(_environment.WebRootPath + "\\upload\\"))
                        {
                              Directory.CreateDirectory(_environment.WebRootPath + "\\upload\\");
                }
                using (FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\upload\\" + filename))
            {
                source.CopyTo(fileStream);
                fileStream.Flush();
                return "\\upload\\" + source.FileName;
            }
        }
        return "true";

        }
        catch (Exception ex)
        {

            throw;
        }
        
    }

文件始终显示为空。

标签: javascriptapiasp.net-web-apixmlhttprequest

解决方案


尝试

    xmlHttpRequest.open('POST', target, true);
    xmlHttpRequest.send(new FormData(fInput.form));

推荐阅读