Angular upload 405 (Method Not Allowed)

2019-09-10 06:09发布

问题:

When try upload images with angular get error 405 (Method Not Allowed)

Online example

I'm change headers im my source but again error, any solution?

When change URL to https://angular-file-upload-cors-srv.appspot.com/upload work fine on my destination not working!

回答1:

Your destination needs to be Web API that handles POST. Something like that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace WebAPI.Controllers
{
public class FileUploadController : ApiController
{

    public HttpResponseMessage Post()
    {
        HttpResponseMessage result = null;
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {
            var docfiles = new List<string>();
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = HttpContext.Current.Server.MapPath("~/images/" + postedFile.FileName);
                postedFile.SaveAs(filePath);

                docfiles.Add(filePath);
            }
            result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
        }
        else
        {
            result = Request.CreateResponse(HttpStatusCode.BadRequest);
        }
        return result;
    }


}
}

See step-by-step here. If you need asynchronous upload, check out this.

The "~/images/" in the MapPath can be a virtual folder.