Server.MapPath检查文件夹并创建

时间:2014-10-28 11:41:28

标签: model-view-controller

我正在将图片上传到文件夹图片。它工作正常。但我真正想要的是寻找一个文件夹名称(我有文件夹名称)如果没有找到创建该文件夹并给它那个名称。那么可能会发生吗?

这是我到目前为止所做的:

 string ImageName = System.IO.Path.GetFileName(file.FileName);
 string physicalPath = Server.MapPath("~/images/" + ImageName);

而不是图像我应该有folderName。

完整的视图

@{
ViewBag.Title = "Index";
}


@using (Html.BeginForm("FileUpload", "datum", FormMethod.Post,
                new { enctype = "multipart/form-data" }))
{
<div>
   category<br />
   @Html.DropDownList("category", ViewBag.Roles as SelectList)
 <br/>
   description<br />
    @Html.TextBox("description") <br />
    Image<br />
    <input type="File" name="file" id="file" value="Choose File" />
    <input type="submit" value="Upload" class="submit" />
</div>
 }

完整的控制器

 public class datumController : Controller
 {
    DataEntry db = new DataEntry();
    public ActionResult Index()
    {
        var data = from p in db.categories

                   select p.categoryName;

        SelectList list = new SelectList(data);
        ViewBag.Roles = list;
        return View();
    }
    public ActionResult create ()
    {
        return View();
    }
    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {

        if (file != null)
        {

            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath = Server.MapPath("~/images/" + ImageName);



            // save image in folder
            file.SaveAs(physicalPath);

            //save new record in database
           datum newRecord = new datum();
            newRecord.category = Request.Form["category"];
            newRecord.description = Request.Form["description"];
            newRecord.imagePath = ImageName;
            db.data.Add(newRecord);
            db.SaveChanges();


        }
        //Display records
        return RedirectToAction("Display");
    }

所以我应该从下拉列表中获取所选值并将其附加到物理路径,如果没有,则检查文件夹是否存在然后创建文件夹并将图像上传到该文件夹​​

2 个答案:

答案 0 :(得分:0)

尝试如下...

  string subPath ="ImagesPath"; // your code goes here

  bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

  if(!exists)
  System.IO.Directory.CreateDirectory(Server.MapPath(subPath));

有关详细信息,请参阅以下链接。 If a folder does not exist, create it

答案 1 :(得分:-1)

if (file != null && file.ContentLength > 0) 
{
    string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
    tbl_MixEmp.EmpImage = Path.Combine("~/Images", file.FileName);
    file.SaveAs(path);
}