Search code examples
ajaxasp.net-mvcjquery-file-upload

File Upload from Ajax Saving to Subdirectory


I am trying to get the files uploaded from a ajax request, using ASP MVC, to save in my projects document folder, under a sub folder. Say for instance I get the files from the Request Object, for each set of files, I want to create an individual folder under Documents, each time to store the files. I have tried the code below but it throws an exception, stating, Could not find part of the path. I am assuming it is the sub directory I'm trying to store the files in and I've tried all sorts of combination, with no avail. Any help would be appreciated, as I have been trying to figure this out all morning.

My rootPath is stored in my config file as C:\21Vianet\21Vianet\Documents

        if (Request.Files.Count > 0)
        {
            var rootPath = ConfigurationManager.AppSettings["DocumentsPath"];
            if (!(Directory.Exists(rootPath)))
            {
                Directory.CreateDirectory(rootPath);
            }

            var claimPath = Path.Combine(rootPath, claimNumber.ToString());
            Directory.CreateDirectory(claimPath);

            try
            {
                //  Get all files from Request object  
                HttpFileCollectionBase files = Request.Files;
                for (int i = 0; i < files.Count; i++)
                { 

                    HttpPostedFileBase file = files[i];
                    string fname;
                    fname = file.FileName;
                    var filePath = Path.Combine(claimPath, file.FileName);
                    fname = Path.Combine(filePath, fname);
                    file.SaveAs(fname);
                }
            catch (Exception ex)
            {

            }
         }

Solution

  • Try adding Directory.CreateDirectory(filePath);

    after

    var filePath = Path.Combine(claimPath, file.FileName);

    The last created directory was: \Documents\claimNumber, but you're trying to save a file to: \Documents\claimNumber\fileName\