通过ajax发送字节数组

Closed. This question needs debugging details. It is not currently accepting answers.
                </div>
            </div>
        </div>
                <hr class="my12 outline-none baw0 bb bc-powder-2">
            <div class="grid fw-nowrap fc-black-600">
                    <div class="grid--cell mr8">
                        <svg aria-hidden="true" class="svg-icon iconLightbulb" width="18" height="18" viewbox="0 0 18 18"><path d="M9.5.5a.5.5 0 0 0-1 0v.25a.5.5 0 0 0 1 0V.5zm5.6 2.1a.5.5 0 0 0-.7-.7l-.25.25a.5.5 0 0 0 .7.7l.25-.25zM1 7.5c0-.28.22-.5.5-.5H2a.5.5 0 0 1 0 1h-.5a.5.5 0 0 1-.5-.5zm14.5 0c0-.28.22-.5.5-.5h.5a.5.5 0 0 1 0 1H16a.5.5 0 0 1-.5-.5zM2.9 1.9c.2-.2.5-.2.7 0l.25.25a.5.5 0 1 1-.7.7L2.9 2.6a.5.5 0 0 1 0-.7z" fill-opacity=".4"></path><path opacity=".4" d="M7 16h4v1a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1v-1z" fill="#3F3F3F"></path><path d="M15 8a6 6 0 0 1-3.5 5.46V14a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-.54A6 6 0 1 1 15 8zm-4.15-3.85a.5.5 0 0 0-.7.7l2 2a.5.5 0 0 0 .7-.7l-2-2z" fill="#FFC166"></path></svg>
                    </div>
                <div class="grid--cell lh-md">
                    <p class="mb0">
                        <b>Want to improve this question?</b> <a href="/posts/55931969/edit">Update the question</a> so it's <a href="/help/on-topic">on-topic</a> for Stack Overflow.
                    </p>
                    <p class="mb0 mt6">Closed <span title="2019-05-01 16:40:06Z" class="relativetime">12 months ago</span>.</p>
                </div>
            </div>
    </aside>

I am having ajax request which is working only half way.

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");
        }
    });
}

Here is my request. As you can see i commented up there that in my test(alert) fr.result has value BUT when i debug and go see it in my controller, it is NULL.

Here is my controller.

[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);
    }
}
</div>

Your're using ajax in a wrong way.

  1. The first error is a mismatch with Content-Type

    $.ajax({
        ...
        contentType: "application/json; charset=utf-8",
        ...
        data: {
            byteArray: fr.result,
            fileName: $('input[type=file]').val().split('\\').pop()
        },
        ...
    } 
    

    Although you've set the Content-Type=application/json, the payload sent to server will be form-url-encoded by default:

    fileName=Xyz&byteArray=
    

    If you need JSON format, you should use JSON.stringify({...}) to get a text representation.

  2. The contentType: "application/json; is not suitable here. That's because :

    • The JSON is not designed to deal with binary data but used for text. You can't send a byte[] with json.
    • The server side code expects simple type from query/routes/form. If you need json, they should be something like IActionResult UploadImage([FromBody] Fr fr)
  3. If you're sending an image, the easiest way is to use the Content-Type of multipart/form-data with the IFormFile on the server side at the same time.

    // action method
    public IActionResult UploadImage(IFormFile image, string fileName)
    {
         // ...
    }
    

    and now you could send a 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 () {
                // ...
            }
        });
    }
    

That would be your idea:

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);
    }
}

Your problem is that you not post as byte[] but you have to post as string !