-1

i am trying to upload the file from frontend on button click not as form submit. i am getting error like "is a physical path, but a virtual path was expected." i have tried server.mapPath option still there is no luck.actually i want to save the file path in to DB from front end using ajax.

$('#PEsubmit').click(function(){

        var Companyname = '';
        var flg = 0;
        var Startdate = '';
        var enddate = '';
        var path = '';

        $('#PriorExperienceAdd  tr').each(function () {
            if (flg > 0) {

                Companyname += $(this).find("td:eq(0)").find('input[type=text]').val();
                Companyname +='&'

                Startdate += $(this).find("td:eq(1)").find('input[type=text]').val();
                Startdate += '~';

                enddate += $(this).find("td:eq(2)").find('input[type=text]').val();
                enddate += '#';

                path += $(this).find("td:eq(3)").find('input[type=file]').val();
                path += '%';
            }
            flg++;


        });
        if (Companyname.length > 1) {
            Companyname = Companyname.substring(0, Companyname.length - 1);
        }
        if (Startdate.length > 1) {
            Startdate = Startdate.substring(0, Startdate.length - 1);
        }
        if (enddate.length > 1) {
            enddate = enddate.substring(0, enddate.length - 1);
        }
        if (path.length > 1) {
            path = path.substring(0, path.length - 1);
        }

        var Pathdetails={
            "CompName": Companyname,
            "StartDate": Startdate,
            "EndDate": enddate,
            "Path": path,
        };

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

        }
    });//ajaxends

        });




public void AddPriorExperience(string CompName, string StartDate, String EndDate, string Path, string filename)
        {

             CheckUser Sessiondetails = new CheckUser();
             int SessionRolevalue = Sessiondetails.CheckSessionuser();
             if (SessionRolevalue != 0)
            {
                using (EMSOffshoreEntities DB = new EMSOffshoreEntities())
                {
                    DB.Database.Connection.Open();
                    AccountModel AccModel = new AccountModel();
                    int loginId = Convert.ToInt32(Decrypt.AESDecryptstring(Convert.ToString(Session["LoginId"])));
                    int selectedUserId = Convert.ToInt32(Decrypt.AESDecryptstring(Convert.ToString(Session["SelectedUser"])));
                    List<Sp_GetPriorExperience_Result> PriExp = DB.Sp_GetPriorExperience(selectedUserId).ToList();
                    List<Sp_GetSelectedUserDetail_Result> userdet = DB.Sp_GetSelectedUserDetail(selectedUserId).ToList();
                    string Username = userdet.First().UserName;
                    AccModel.PriorExperience = PriExp;
                    CompName = CompName.Replace("undefined", "");
                    StartDate = StartDate.Replace("undefined", "");
                    EndDate = EndDate.Replace("undefined", "");
                    Path = Path.Replace("undefined", "");
                    Path = Path.Replace(" ", "");
                    string filetype="";
                    string[] pathspl = Path.Split('%');
                    string subPath = "~/Documents/PriorExperience/" + selectedUserId + "-" + Username + "/" + filetype + "/";
                    string filePath = System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"] + "~/Documents/PriorExperience/" + selectedUserId + "-" + Username + "/" + filetype + "/";
                    bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
                    if (!exists)
                        System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
                    string rootFolderPath = Path;
                    rootFolderPath = rootFolderPath.Replace(System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"], "");
                    string flpth = rootFolderPath;
                    flpth = flpth.Replace(@"\PriorExperience", "");
                    string subpath1 = Server.MapPath(subPath + filename);
                    subpath1 = subpath1.Replace(@"\PriorExperience", "");
                    if (System.IO.File.Exists(flpth))
                    {
                        System.IO.File.Move((flpth), (subpath1));
                        filePath = filePath + Path;
                        //objdoc.SP_DeleteBasicDocs(userid, Convert.ToInt32(id), loginid, filePath);
                    }

                    DB.Database.Connection.Close();
                }
            }
            else
            {
              Redirect(ConfigurationManager.AppSettings["BaseUrl"] + "Account/Login");
            }

        }
  • To upload files using ajax, use `FormData` and set the correct ajax options (refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681)) –  Nov 02 '16 at 12:22
  • i am not using form tag to access FormData . can i get give some other solution? – Sindhuja Selvam Nov 02 '16 at 12:26
  • 1
    You do not seem to have any understanding of your code. A file input posts back to type of `HttpPostedFileBase` - not a `string`. And nothing else your doing makes any sense. You need to go to the MVC site and learn the basics, in particular how to generate you view correctly by binding to a model and allowing you to post back that model –  Nov 02 '16 at 12:30

1 Answers1

2

Posting a file path is not the same thing as uploading a file. The server cannot make a request from the client, so there's no possible way to actually do anything with a file path from a client's machine. The client must actually provide the server with the file data. That is how an upload is performed.

To upload a file with AJAX requires HTML 5 features. That means right off the bat that your AJAX upload will only work in modern browsers. In other words, if you need to support something like IE 7-9, then this method is out entirely. Your only option in that case is to either do a traditional form post or use some sort of Flash or Java control.

Assuming you can focus entirely on modern browsers, then you'll need code along the lines of the following:

$('#MyForm').on('submit', function (e) {
    e.preventDefault();
    var formData = new FormData(this); // `this` is the form instance
    $.ajax({
        url: '/path/to/handler',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        success: function (data, textStatus, jqXHR) {
            // do something on success
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // do something on error
        }
    });
});

On the MVC side, you'll need to bind the file input to a property of type HttpPostedFileBase.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • so the conclusion is there is no way to take a file from client to server by using ajax ?? – Sindhuja Selvam Nov 02 '16 at 13:22
  • Umm.. no; that's not what I said at all. I said the way you're *trying to do it* doesn't work. However, with HTML 5, you can definitely upload a file via AJAX, but only utilizing HTML 5. If you must support IE 7-9, then effectively, there's no way to upload a file via AJAX because those versions do not support the necessary HTML 5 features. – Chris Pratt Nov 02 '16 at 13:24
  • yes i got it. u r saying like it will not work in IE lower versions. so u suggesting me to do with HttpPostedFileBase. is there any other way to do with ajax without form submit? – Sindhuja Selvam Nov 02 '16 at 13:31
  • If you need to support IE 7-9, then you cannot do an AJAX upload. Period. Your only option is to do a normal form submit, or employ a Flash/Java-based third-party solution. – Chris Pratt Nov 02 '16 at 13:33
  • Thank u so much for guiding Flash/Java-based means? – Sindhuja Selvam Nov 02 '16 at 13:38
  • Flash, as in Adobe Flash. Java, as in the runtime from Oracle. Since the browsers you need to support do not have the requisite features, you need some sort of plugin. Both Flash and Java have browser plugins available that enable applications built with either Flash or Java to do things within the browser, such as accept a file from a user and automatically upload it to a server. However, the client must choose to install the requisite plugins *and* choose to allow them to run on your site. That's the best you can do in this scenario though. – Chris Pratt Nov 02 '16 at 13:43