0

I am trying to implement the file upload feature in my asp.net mvc web application. But when i try to retrieve the file from the input tag through js, it is always returning null. I am using ajax to send files to the server from my partial view, and the control is successfully getting transferred to the controller but the file is always null. Any help would be appreciated. Thank You.

Partial View

@using (Html.BeginForm("FileUpload",
    "Home",
    FormMethod.Post,
    new { enctype = "multipart/form-data" }))
    {
        <div id="uploadbutton" style="top:50%;position:absolute;height:120px;width:300px;border-width:2px;border-style:dotted;border-radius:20px;display:flex;align-items:center;justify-content:center">
            <div style="width:100px;flex-direction:row;display:flex;align-self:center;position:absolute;left:10px">
                <label style="margin-right:10px" for="file">Upload:</label>
                <input type="file" name="file" id="file" /><br><br>
                <br><br>
                @ViewBag.Message
            </div>
        </div>
        <button type="submit" id="ProcessButton" style="position:absolute;top:75%;background-color:cornflowerblue;color:brown;border-color:brown;height:40px;width:100px">Process</button>
    }

Js code

        var fileUpload = $("#file").get(0);
        var files = fileUpload.files;
        // Create FormData object  
        var fileData = new FormData();

        // Looping over all files and add it to FormData object  
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }

        $.ajax({
            url: '@Url.Action("FileUpload", "Home")',
            type: 'POST',
            cache: false,
            async: true,
            data: JSON.stringify(fileData),
            contentType: false,
            processData: false,
            success: function (result) {
                alert('cool');
            }
        });

Controller

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {

         
    }
    else
    {

    }
    return View();
}
Kunal
  • 83
  • 1
  • 10
  • Are you having `partial view` added multiple times in your `view`? Also inside `$.ajax` try with `data: fileData,` instead of `data: JSON.stringify(fileData),`. – Karan Jun 29 '20 at 08:08
  • No i am adding the partial view just once. I tried using just filedata too, but the problem is the filedata is still null. – Kunal Jun 29 '20 at 08:40
  • How could `filedata` be `null`? As you already set `var fileData = new FormData();`. Have you tried `begugging` your javascript code? – Karan Jun 29 '20 at 08:45
  • Sorry by null i mean its empty. After the for loop when i try to console log filedata it is empty. – Kunal Jun 29 '20 at 09:00
  • Btw when i use just filedata in ajax instead of json.stringify, the call never reaches the controller. – Kunal Jun 29 '20 at 09:08
  • Though it will show `empty object`, it will be holding your uploaded `file`. To check it you can try logging like `fileData.get(files[0].name)` before `$.ajax`. – Karan Jun 29 '20 at 09:18
  • Or you can see all your files with `for(var pair of fileData.entries()) { console.log(pair[0]+ ', '+ pair[1]); }`. – Karan Jun 29 '20 at 09:21
  • You are right. FileData does have the uploaded file. So i guess ajax is sending null to the controller? – Kunal Jun 29 '20 at 10:26
  • Try with `data: fileData,` & `Request.Files` like mentioned in this answer https://stackoverflow.com/a/25125284/9695286 – Karan Jun 29 '20 at 10:48
  • Hey, it started working with this. Thanks a lot. Why does it not work when passed as a parameter to the actionresult? – Kunal Jun 30 '20 at 07:19
  • Also is there any way i can send a string data along with the formdata through my ajax request? – Kunal Jun 30 '20 at 07:22
  • 1
    I guess you may need to append file with name as `file` because your action has parameter name `file`. Try with `fileData.append("file", files[i]);`. Also Check https://stackoverflow.com/a/54396206/9695286. It has `Working Code` section it may help you understand more. – Karan Jun 30 '20 at 08:08
  • @Kunal your issue is solved or not? – Raju Jul 01 '20 at 11:22
  • 1
    Yes it is. Thanks @Karan – Kunal Jul 01 '20 at 14:10

0 Answers0