0

I am trying to add file to my database but for some reason its not working can someone tell me why. This is what I've sofa:

        $(document).on("click", "#BUTTON", function () {
        var FILE= $('#name').val();

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "@Url.Action("File", "Controller")",
            data: JSON.stringify(FILE),
        contentType: "application/json; charset=utf-8",
        success: function () {

        }
    });
    });

This is what happens in my controller:

public ActionResult File(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(Server.MapPath("~/path"), pic);
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return Index();
    }
}

When I place a brakepoint in line HttpPostedFileBase file then file has null value I dont know why? If i do alert(FILE); then I am getting full file path e.g. G:/filename/imagename.jpg but in controller the path is no being passed?

2 Answers2

0

You will not be able to post a file that way, the only thing you do is post the text value, in this case the file name.

Maybe this can help you out (another example on stack overflow)

Community
  • 1
  • 1
Steven
  • 1,444
  • 17
  • 23
0

You can do this if you will use files collection of your input, so try it. And i hope it will help

$(document).on("click", "#BUTTON", function(){

//Create form data
var data = new FormData(); 

//attach your file
data.append('file', document.getElementById("fileHere").files[0]); 

//and send it on server
$.ajax({
    url: "@Url.Action("File", "Controller")",
    data: data,
    cache: false,
    contentType: 'multipart/form-data',
    processData: false,
    type: 'POST',
    success: function(data){
            }
        });
    });
Baximilian
  • 885
  • 7
  • 25
  • When I run the code I get error message `JavaScript runtime error: Unable to get property 'files' of undefined or null reference`. In this line ` data.append('file', document.getElementById("#name").files[0]); ` –  Jul 15 '14 at 09:02
  • getElementById() using DOM not Jquery selector. So remove # and just type id like this document.getElementById("name") – Baximilian Jul 15 '14 at 09:06