跨域图像文件上传使用CORS - ASP。NET Web API和jQuery。

时间:2021-08-24 12:19:27

I am in a need of uploading cross-domain images using ASP.NET web API and AJAX. I am new to this approach.

我需要使用ASP上传跨域图像。NET web API和AJAX。我对这种方法不熟悉。

HTML

HTML

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta charset="utf-8" />
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" id="fileUpload" />
        <input type="submit" value="Upload CORS image" id="btnUpload" />
    </form>
    <div id="response"><!-- AJAX Response --></div>
    <script type="text/javascript">
        //55622
        jQuery.support.cors = true;
        function uploadFile() {
            var fa = new FormData();
            fa.append("upload_pass", document.getElementById("fileUpload").files[0]);
            $.ajax({
                type: "POST",
                url: "http://localhost:5000/api/upload/imagefile",
                data: fa,
                contentType: false,
                processData: false,
                //dataType: "jsonp",
                crossDomain: true,
                success: function (data) {
                    // do something here.
                }
            });
        }
        $(document).ready(function () {
            $("#btnUpload").bind("click", function () {
                uploadFile();
            });
        });
    </script>
</body>
</html>

API Controller Method

API控制器方法

using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Mvc;

namespace WebApiz.Controllers
{
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        [EnableCors("AllowAll")]
        [Route("imagefile")]
        [HttpPost("imagefile")]
        public string ImageFile(object data)
        {
            return data.ToString();
        }
    }
}

I have other Controller methods which are perfectly working with [EnableCors("AllowAll")] but this one is giving me the following error:

我有其他的控制器方法,这些方法与[EnableCors("AllowAll"])完全一致,但是这个方法给了我以下错误:

HTTP Error 405.0 - Method Not Allowed The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.

HTTP错误405.0 -方法不允许您正在查找的页面被显示,因为正在使用一个无效的方法(HTTP动词)。

I have absolutely no idea how to solve this! I referred to this and this. But honestly I did not understand clearly. If somebody please help me with what I am doing wrong and what I need to do to accomplish this that would a life saver for me!

我完全不知道怎么解决这个问题!我提到了这个和这个。但老实说,我不太明白。如果有人帮我做错了什么,我需要做什么来完成这一切,那将是我的救命恩人!

Thanks in advance.

提前谢谢。

2 个解决方案

#1


2  

I tried a few things and finally this works for me.

我尝试了一些东西,最后这对我很有效。

HTML

HTML

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta charset="utf-8" />
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" id="fileUpload" name="fileUpload" multiple="multiple" />
        <input type="button" value="Upload CORS image" id="btnUpload" />
    </form>
    <div id="response"><!-- AJAX Response --></div>
    <script type="text/javascript">
        jQuery.support.cors = true;

        function uploadFiles(url) {
            var data = new FormData();

            var files = $("#fileUpload").get(0).files;

            // Add the uploaded image content to the form data collection
            if (files.length > 0) {
                for (var f = 0; f < files.length; f++) {
                    data.append("UploadedImage", files[f]);
                }
            }

            // Make Ajax request with the contentType = false, and procesDate = false
            $.ajax({
                type: "POST",
                url: url,
                contentType: false,
                processData: false,
                data: data,
                success: function (response) {
                    $("#response").html(response);
                }
            });
        }

        $(document).ready(function () {
            $("#btnUpload").bind("click", function () {
                uploadFiles("http://localhost:5000/api/upload/fileupload");
            });
        });
    </script>
</body>
</html>

Controller

控制器

using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Net.Http.Headers;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace ProjectApi.Controllers
{
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        private IHostingEnvironment _environment;
        public UploadController(IHostingEnvironment environment)
        {
            _environment = environment;
        }

        [EnableCors("AllowAll")]
        [Route("fileupload")]
        [HttpPost("fileupload")]
        public async Task<object> FileUpload()
        {
            var httpRequest = HttpContext.Request;
            var imageUrls = string.Empty;
            var fileName = string.Empty;

            if (httpRequest.Form.Files.Count > 0)
            {
                var uploads = Path.Combine(_environment.WebRootPath, "uploads");
                for (var f = 0; f < httpRequest.Form.Files.Count; f++)
                {
                    var postedFile = httpRequest.Form.Files[f];
                    var files = new List<IFormFile>();
                    files.Add(postedFile);

                    foreach (var file in files)
                    {
                        fileName = ContentDispositionHeaderValue.Parse(postedFile.ContentDisposition).FileName.Trim('"');
                        var fileExtension = fileName.Substring(fileName.LastIndexOf("."));
                        var randomFileName = System.DateTime.Now.Ticks.ToString();
                        var finalFileName = randomFileName + fileExtension;

                        await file.SaveAsAsync(Path.Combine(uploads, finalFileName));
                        imageUrls += "<img src='http://localhost:5000/uploads/" + finalFileName + "' alt='' /><br />";
                    }
                }

                return imageUrls;
            }

            return "No image were uploaded";
        }
    }
}

Thank you esiprogrammer for showing me the way. However I did not use any custom model.

谢谢你给我带路。但是我没有使用任何自定义模型。

I also referred to these articles:

我还提到这些条款:

http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/ http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6 http://blog.kotowicz.net/2011/05/cross-domain-arbitrary-file-upload.html

http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/ http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6 http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6

#2


1  

you need to set parameters of EnableCors attribute

您需要设置EnableCors属性的参数

To allow all methods, use the wildcard value “*”. The following example allows only GET and POST requests.

要允许所有方法,请使用通配符值“*”。下面的示例只允许GET和POST请求。

[EnableCors(origins: "http://localhost:5000", headers: "*", methods: "get,post")]

enable CORS using web.config:

使歌珥使用web . config:

following example Allow CORS for all origins

下面的示例允许所有起源都使用CORS

<system.webserver>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST" />
      </customHeaders>
    </httpProtocol>
</system.webserver>

#1


2  

I tried a few things and finally this works for me.

我尝试了一些东西,最后这对我很有效。

HTML

HTML

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta charset="utf-8" />
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" id="fileUpload" name="fileUpload" multiple="multiple" />
        <input type="button" value="Upload CORS image" id="btnUpload" />
    </form>
    <div id="response"><!-- AJAX Response --></div>
    <script type="text/javascript">
        jQuery.support.cors = true;

        function uploadFiles(url) {
            var data = new FormData();

            var files = $("#fileUpload").get(0).files;

            // Add the uploaded image content to the form data collection
            if (files.length > 0) {
                for (var f = 0; f < files.length; f++) {
                    data.append("UploadedImage", files[f]);
                }
            }

            // Make Ajax request with the contentType = false, and procesDate = false
            $.ajax({
                type: "POST",
                url: url,
                contentType: false,
                processData: false,
                data: data,
                success: function (response) {
                    $("#response").html(response);
                }
            });
        }

        $(document).ready(function () {
            $("#btnUpload").bind("click", function () {
                uploadFiles("http://localhost:5000/api/upload/fileupload");
            });
        });
    </script>
</body>
</html>

Controller

控制器

using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Net.Http.Headers;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace ProjectApi.Controllers
{
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        private IHostingEnvironment _environment;
        public UploadController(IHostingEnvironment environment)
        {
            _environment = environment;
        }

        [EnableCors("AllowAll")]
        [Route("fileupload")]
        [HttpPost("fileupload")]
        public async Task<object> FileUpload()
        {
            var httpRequest = HttpContext.Request;
            var imageUrls = string.Empty;
            var fileName = string.Empty;

            if (httpRequest.Form.Files.Count > 0)
            {
                var uploads = Path.Combine(_environment.WebRootPath, "uploads");
                for (var f = 0; f < httpRequest.Form.Files.Count; f++)
                {
                    var postedFile = httpRequest.Form.Files[f];
                    var files = new List<IFormFile>();
                    files.Add(postedFile);

                    foreach (var file in files)
                    {
                        fileName = ContentDispositionHeaderValue.Parse(postedFile.ContentDisposition).FileName.Trim('"');
                        var fileExtension = fileName.Substring(fileName.LastIndexOf("."));
                        var randomFileName = System.DateTime.Now.Ticks.ToString();
                        var finalFileName = randomFileName + fileExtension;

                        await file.SaveAsAsync(Path.Combine(uploads, finalFileName));
                        imageUrls += "<img src='http://localhost:5000/uploads/" + finalFileName + "' alt='' /><br />";
                    }
                }

                return imageUrls;
            }

            return "No image were uploaded";
        }
    }
}

Thank you esiprogrammer for showing me the way. However I did not use any custom model.

谢谢你给我带路。但是我没有使用任何自定义模型。

I also referred to these articles:

我还提到这些条款:

http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/ http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6 http://blog.kotowicz.net/2011/05/cross-domain-arbitrary-file-upload.html

http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/ http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6 http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6

#2


1  

you need to set parameters of EnableCors attribute

您需要设置EnableCors属性的参数

To allow all methods, use the wildcard value “*”. The following example allows only GET and POST requests.

要允许所有方法,请使用通配符值“*”。下面的示例只允许GET和POST请求。

[EnableCors(origins: "http://localhost:5000", headers: "*", methods: "get,post")]

enable CORS using web.config:

使歌珥使用web . config:

following example Allow CORS for all origins

下面的示例允许所有起源都使用CORS

<system.webserver>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST" />
      </customHeaders>
    </httpProtocol>
</system.webserver>