Upload with ASP.NET Core json vs formdata

Asked

Viewed 1,253 times

3

I’m using Asp.net core webapi, initially my actions were using the attribute [Frombody] in the parameters, so I rescued the json value sent by front-end. I am now implementing a screen that has upload, and I had to use formdata to send the file, and at that moment I inserted my object (which I used to send as json) in my formdata. That way, I needed to change my back-end to accept the formdata, just remove the [Frombody].

I wish I could use my action, either passing formdata or passing a json, is that possible? How?

1 answer

1

I can illustrate with Minimal Example, because, it does not have so many details specific in the question and about the question of action be responsible for both types to receive the information and the file unfortunately does not, what can be done is as an example below, for a send with jQuery + FormData and another Action who receives json with [FromBody].

I have a class Elemento:

public class Elemento
{
    public int Id { get; set; }
    public string Nome { get; set; }
}

and a form on the page beyond with the two fields, will be passed via an image of a input type file with FormData:

  • <form>

    <form name="form1" id="form1">
        <input type="text" name="Id" value="1" />
        <input type="text" name="Nome" value="@Guid.NewGuid()" />
        <input type="file" name="arquivo" id="arquivo" />
        <button type="button" onclick="send()">Enviar</button>
    </form>
    
  • ajax

    function send() {
        var items = ($("#form1").serializeArray());
        var form = new FormData();
        for (i = 0; i < items.length; i++)
        {
            form.append(items[i].name.toLocaleLowerCase(), items[i].value);
        }
        form.append('arquivo', $('#arquivo')[0].files[0]);            
        $.ajax({
            type: "POST",
            url: "/api/Elementos",
            contentType: false,
            processData: false,
            data: form,
            success: function (message) {
                // code
            },
            error: function () {
                //code
            }
        });
    }
    
  • controller/action

    [HttpPost]
    public IActionResult Post(Elemento elemento,IFormFile arquivo)
    {
        // aqui também recupera
        var resultForm = Request?.Form;
    
        // aqui de forma automática
        var ele = elemento;
        var arq = arquivo; // a foto enviado            
        return Ok(new { e = elemento });
    }
    

Code of the full page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebApplication2</title>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
    <h2>Index</h2>
    <form name="form1" id="form1">
        <input type="text" name="Id" value="1" />
        <input type="text" name="Nome" value="@Guid.NewGuid()" />
        <input type="file" name="arquivo" id="arquivo" />
        <button type="button" onclick="send()">Enviar</button>
    </form>
    <script>
        function send() {
            var items = ($("#form1").serializeArray());
            var form = new FormData();
            for (i = 0; i < items.length; i++)
            {
                form.append(items[i].name.toLocaleLowerCase(), items[i].value);
                console.log(items[i].name.toLocaleLowerCase() + ':' + items[i].value);
            }
            form.append('arquivo', $('#arquivo')[0].files[0]);            
            $.ajax({
                type: "POST",
                url: "/api/Elementos",
                contentType: false,
                processData: false,
                data: form,
                success: function (message) {
                    alert(message);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        }
    </script>
</body>
</html>

Debug performed for testing:

inserir a descrição da imagem aqui


inserir a descrição da imagem aqui

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.