0

I need to upload a file from my file input through ajax with multiple parameters through an ASP.NET MVC controller and I am getting an error. Save file from input to variable data2.

var data2 = new FormData();
var files;

var loadFile = function (event) {
     files = $("#upload").get(0).files;
    if (files.length > 0) {
        data2.append("MyImages", files[0]);
    }
};

Send data with ajax

 $.ajax({
        url: "/Adot/UploadAdopt",
        type: "POST",
        data: { ForUpload:data2,
                 Title:"New name"},
        success: function (response) {
            console.log(response);
        }
    });

Controller

[HttpPost]
public JsonResult UploadAdopt(HttpPostedFileBase ForUpload, string Title)
{
        string path = Path.Combine(Server.MapPath("~/image/adopts"), Path.GetFileName(ForUpload.FileName));
        ForUpload.SaveAs(path);
        return Json("", JsonRequestBehavior.AllowGet);
}
5
  • What exactly is the error message you get? Can you share the html as well. Commented Sep 16, 2022 at 18:16
  • @Jasen I have error 'Uncaught TypeError: Illegal invocation' Commented Sep 16, 2022 at 18:22
  • 2
    See this answer stackoverflow.com/a/52416731/2030565 Commented Sep 16, 2022 at 18:27
  • This solved my problem. But I still didn't get it, why I should use append and can't use multiple data ajax parametrs and simply pass a file type as a parametr into controller, as I usualy do with any other data types(string, int, bool)? Commented Sep 17, 2022 at 6:06
  • When you want to send file plus an additional payload, we use multipart/form-data. The FormData interface provides an easy way to construct this type of request. developer.mozilla.org/en-US/docs/Web/API/FormData Commented Sep 20, 2022 at 1:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.