我有ajax请求只有一半的工作。
function receivedText() {
alert(fr.result); //Here i have good result
$.ajax({
type: "POST",
url: "/Gallery/UploadImage",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
byteArray: fr.result,
fileName: $('input[type=file]').val().split('\\').pop()
},
success: function (data) {
if (data == 0)
alert("error");
else
alert("Success");
},
error: function () {
alert("ERROR");
}
});
}
这是我的要求。你可以看到我在那里评论说,在我的测试(警报)中,fr.result
有价值但是当我调试并在我的控制器中看到它时,它是NULL。
这是我的控制器。
[HttpPost]
public IActionResult UploadImage(byte[] byteArray, string fileName)
{
try
{
System.IO.File.WriteAllBytes(_hostingEnvironment.WebRootPath + "\\Uploads\\Images\\" + fileName, byteArray);
return Json(0);
}
catch
{
return Json(0);
}
}
你以错误的方式使用ajax。
Content-Type
不匹配
$.ajax({
...
contentType: "application/json; charset=utf-8",
...
data: {
byteArray: fr.result,
fileName: $('input[type=file]').val().split('\\').pop()
},
...
}
虽然您已设置Content-Type=application/json
,但默认情况下,发送到服务器的有效负载将为form-url-encoded
:
fileName=Xyz&byteArray=
如果您需要JSON格式,则应使用JSON.stringify({...})
来获取文本表示。contentType: "application/json;
不适合这里。那是因为 :
JSON不是用来处理二进制数据而是用于文本。你不能用json发送byte[]
。
服务器端代码需要来自查询/路由/表单的简单类型。如果你需要json,它们应该像IActionResult UploadImage([FromBody] Fr fr)
Content-Type
的multipart/form-data
和IFormFile
。
// action method
public IActionResult UploadImage(IFormFile image, string fileName)
{
// ...
}
现在你可以发送一个FormData
:
// your receivedText() function
function receivedText(){
var formData = new FormData();
formData.append('fileName', 'Xyz.img');
// if you need upload image
var inputFileElement=document.getElementById("inputFileImage");
formData.append('image', inputFileElement.files[0]);
// of if you're already have a `byte[]`, you could do it as below:
// var blob = new Blob([bytearray]...); // see https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
// formData.append('image', blob);
$.ajax({
type: "POST",
url: "/Gallery/UploadImage",
contentType: false,
processData: false,
data: formData,
success: function (data) {
console.log(data);
// ...
},
error: function () {
// ...
}
});
}
那是你的想法:
public class UploadImageBindings {
public string byteArray {get;set;}
public string fileName {get;set;}
}
[HttpPost]
public IActionResult UploadImage(UploadImageBindings bindings)
{
try
{
var bytes = System.Text.Encoding.UTF8.GetBytes(bindings.byteArray);
System.IO.File.WriteAllBytes(_hostingEnvironment.WebRootPath + "\\Uploads\\Images\\" + bindings.fileName, bytes);
return Json(0);
}
catch
{
return Json(0);
}
}
你的问题是你不发布为byte[]
但你必须发布为字符串!