通过ajax发送字节数组[关闭]

问题描述 投票:0回答:2

我有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);
    }
}
javascript jquery ajax asp.net-core
2个回答
1
投票

你以错误的方式使用ajax。

  1. 第一个错误是与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-encodedfileName=Xyz&byteArray= 如果您需要JSON格式,则应使用JSON.stringify({...})来获取文本表示。
  2. contentType: "application/json;不适合这里。那是因为 : JSON不是用来处理二进制数据而是用于文本。你不能用json发送byte[]。 服务器端代码需要来自查询/路由/表单的简单类型。如果你需要json,它们应该像IActionResult UploadImage([FromBody] Fr fr)
  3. 如果您要发送图像,最简单的方法是在服务器端同时使用Content-Typemultipart/form-dataIFormFile// 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 () { // ... } }); }

1
投票

那是你的想法:

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[]但你必须发布为字符串!

© www.soinside.com 2019 - 2024. All rights reserved.