Issue
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 class="mb-3">
                    <label for="exampleFormControlInput1" class="form-label">Title</label>
                    <input asp-for="Name" name="name" type="text" class="form-control" id="name" placeholder="Document Title" required>
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
                <div class="mb-3">
                    <label for="exampleFormControlTextarea1" class="form-label">Description</label>
                    <textarea asp-for="Description" class="form-control" placeholder="Document Description" id="description" rows="3"></textarea>
                </div>
                <input type="hidden" name="Size" value="@Size" />
                <div class="mb-3">
                    <label for="formFile" class="form-label">Select Document</label>
                    <input class="form-control" id="files" name="files" asp-for="documents" type="file">
                    <span asp-validation-for="documents" class="text-danger"></span>
                </div>
                <button type="submit" id="upload" class="btn btn-primary" onclick="uploadFile()"><i class="fas fa-plus"></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?
Solution
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(IFormFile file,[FromForm] string name,[FromForm] string description)
    {
      // use the stream object
      Stream stream = file.OpenReadStream();
      
      // use the name and description
      // something here...
    }
Answered By - HsuTingHuan Answer Checked By - Mildred Charles (PHPFixing Admin)
 
 Posts
Posts
 
 
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.