반응형

.cshtml (razor page)

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

Controller

(HomeController.cs)

public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

이러면 /content/files/contact/ 의 경로에 이미지파일들이 업로드 된다.

날짜와 사용자의 index 등을 잘 조합해서 중복되지 않는 파일명을 만들어 업로드하고 

DB에 경로를 지정해주면 될것입니다.

 

출처 : https://stackoverflow.com/questions/16255882/uploading-displaying-images-in-mvc-4

반응형

+ Recent posts