Home > OS >  How can I append strings to Ajax formData together with a file
How can I append strings to Ajax formData together with a file

Time:08-19

I am trying to append strings when am sending my form to an Asp Net Core API. I have a file input which I am successfully getting and uploading to the server but now the problem is I am failing to append extra string like name and file description and getting them on the back-end. So far I tried appending directly into the form data like below:

The JS

var name = document.getElementById("name").value;
        var description = document.getElementById("description").value;
        var data = new FormData();
        data.append(files[0].name, files[0]), name, description);

The backend

[HttpPost]
    [Route("Upload")]
    public async Task<ActionResult> AddDocuments([FromForm]string name, [FromForm] string description)
    {
        var file= Request.Form.Files;

When I do the above am getting null variables of the name and description in my controller. Below is the full code:

Form

                <form method="POST" enctype="multipart/form-data" id="myform">
                <div >
                    <label for="exampleFormControlInput1" >Title</label>
                    <input asp-for="Name" name="name" type="text"  id="name" placeholder="Document Title" required>
                    <span asp-validation-for="Name" ></span>
                </div>

                <div >
                    <label for="exampleFormControlTextarea1" >Description</label>
                    <textarea asp-for="Description"  placeholder="Document Description" id="description" rows="3"></textarea>
                </div>

                <input type="hidden" name="Size" value="@Size" />

                <div >
                    <label for="formFile" >Select Document</label>
                    <input  id="files" name="files" asp-for="documents" type="file">
                    <span asp-validation-for="documents" ></span>
                </div>

                <button type="submit" id="upload"  onclick="uploadFile()"><i ></i> Upload Document</button>
                </form>

Javascript

<script>

function uploadFile() {
    var fileUpload = $("#files").get(0);
    var files = fileUpload.files;
    var name = document.getElementById("name").value;
    var description = document.getElementById("description").value;
    var data = new FormData();
    data.append(files[0].name, files[0]), name, description;
    //data.append(name);
    //data.append(description);
    $.ajax({    
        type: "POST",

        url: "@TempData["api"]api/Document/Upload",
        headers: {
            'Authorization': 'Bearer @HttpContextAccessor.HttpContext.Session.GetString("token")'
        },
            
        contentType: false,
        processData: false,
        data: data,
        async: false,
        beforeSend: function () {
            $("#divloader").show()
        },
        success: function (message) {
            alertify.set('notifier', 'position', 'top-center');
            alertify.success('Successfully uploaded the Document');

            let delay = 5000;
            let url = "/Documents";
            setTimeout(function () {

                location = url;

            }, 5000);
        },
        error: function (e) {
            if (e.responseText == null) {
                e.responseText = "Failed to upload Document. Contact the admin";
            }
            var delay = alertify.get('notifier', 'delay');
            alertify.set('notifier', 'delay', 15);
            alertify.set('notifier', 'position', 'top-center');
            alertify.error(e.responseText);
            alertify.set('notifier', 'delay', delay);
        },
        complete: function () {
            $("#divloader").hide()
        }
    });

}

Controller

[HttpPost]
    [Route("Upload")]
    public async Task<ActionResult> AddDocuments([FromForm]string name, [FromForm] string description)
    {
        var test = Request.Form.ToList();
        var file = Request.Form.Files;

        //Do something with the file and extra data

}

Is there a way I can get the name and description to my controller and access the values?

CodePudding user response:

What if change the javascript code of the data.append() block
like this JS

var data = new FormData();
data.append("file", files[0])
data.append("name", name);
data.append("description", description);

And the .Net Controller's parameter's name MUST be the same as the HTML's formData

the Controller at backend

    [HttpPost]
    [Route("Upload")]
    public async Task<ActionResult> AddDocuments(IFromFile file,[FromForm] string name,[FromForm] string description)
    {
      // use the stream object
      Stream stream = file.OpenReadStream();
      
      // use the name and description
      // something here...
    }
  • Related