简体   繁体   中英

Creating Folder Inside Upload Directory to Save Images

I have a controller method that works fine to upload images in Uploads folder. I try to create a date folder in it, so that I can group the images in relevant date folder. But Directory.CreateDirectory() is not creating a folder inside my existing Uploads Folder. I get an exception on SaveAs() method that

can't find the directory: MyApp/Uploads/10-11-2015

My Action Method

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ProductViewModel productViewModel)
        {
            var ValidImageTypes = new string[]{
                "image/gif",
                "image/jpeg",
                "image/jpg",
                "image/png"
            };

            if(!ValidImageTypes.Contains(productViewModel.ImageUpload.ContentType))
            {
                ModelState.AddModelError("ImageUpload", "Please upload gif / jpg / png");
            }
            if (ModelState.IsValid)
            {
                var product = new Products
                {
                    Name = productViewModel.Name
                };

                var UploadDir = "/Uploads/" + DateTime.Now.ToString("dd/MM/yyyy") + "";
                var FolderUploadDir = DateTime.Now.ToString("dd/MM/yyyy");

                    Directory.CreateDirectory("~/Uploads/" + FolderUploadDir);

                //Saving the image
                productViewModel.ImageUpload.SaveAs(ImagePath);

            return View("Index");
            }

You are using invalid date format string for file/folder name dd/MM/yyyy . Character " / " is not allowed in file/folder names. You may use dd-MM-yyyy instead

I figured it out myself, I needed to provide a proper path of server to the CreateDirectory() method. Following code did the trick

var FolderUploadDir = Server.MapPath("~/Uploads/"+DateTime.Now.ToString("dd-MM-yyyy"));
Directory.CreateDirectory(FolderUploadDir);

尝试在目录地址中使用\\\\而不是/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM