简体   繁体   中英

How can I post file to ASP.NET Web api

I am trying to send an image file from JavaScript Single Page App to ASP.Net Core web api, but I am taking allways null exception from api. Also when I try in Postman, Postman works normally, but I don't want to use form I want to call api and send file without form. Please help me. Here is my code.

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

Image Upload Api..

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

File always shown null.

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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