我需要使用 ASP.NET Web API 和 AJAX 上传跨域图像。我对这种方法很陌生。
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 方法
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();
}
}
}
我还有其他 Controller 方法可以与 [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.
我完全不知道如何解决这个问题!我提到了this和 this 。但说实话我并没有理解清楚。如果有人请帮助我解决我做错的事情以及我需要做什么才能实现这一点,这将是我的救星!
提前致谢。
最佳答案
我尝试了一些方法,最后这对我有用。
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";
}
}
}
谢谢esiprogrammer为我指路。但是我没有使用任何自定义模型。
我还引用了这些文章:
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
关于asp.net - 使用 CORS 的跨域图像文件上传问题 - ASP.NET Web API 和 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35990619/