2014-01-08 4 views
2

선택한 파일을 asp mvc4의 폴더에 업로드하는 기능이 있습니다. 보기 페이지의 코드는aps mvc의 json을 사용하여 이미지 업로드

<form id="form1" method="post" enctype="multipart/form-data" action="EmployeeDetails/Upload"> 
<input type='file' id="imgInp" accept="image/jpeg"/> 
    <p> 
     <input type="submit" value="Upload" class="btn"/> 
    </p> 
</form> 

입니다 그리고 컨트롤러 코드 대신 내가 JSON으로 컨트롤러에 뷰에서 이미지를 보내려면이의

[HttpPost] 
     public ActionResult Upload(HttpPostedFileBase imgInp) 
     { 
      if (imgInp != null && imgInp.ContentLength > 0) 
      { 
       // extract only the fielname 
       var fileName = Path.GetFileName(imgInp.FileName); 
       // store the file inside ~/App_Data/uploads folder 
       var path = Path.Combine(Server.MapPath("~/images/Profile"), fileName); 
       imgInp.SaveAs(path); 
      } 
      return view("Index"); 
     } 

입니다. 또는보기 페이지를 새로 고치지 않고 이미지를 업로드 할 수있는 다른 방법이 있습니까? 당신은 아약스 사용하여 양식을 보낼 수 있습니다

답변

2

...

<form id="login-form"> 
    <input type="file" name="photo" id="files" accept="image/*;capture=camera"> 
    <button type="submit" onclick="submitform()">Submit</button> 
    </form> 

JQuery와 서버에

function submitform(){ 
     var postdata = $('#login-form').serialize();   
     var file = document.getElementById('files').files[0]; 
     var fd = new FormData(); 
     fd.append("files", file); 
     var xhr = new XMLHttpRequest(); 
     xhr.open("POST", "/Home/Index", false); 
     xhr.send(fd);  
    } 

컨트롤러

[HttpPost] 
    public JsonResult Index(FormCollection data) 
    { 

     if (Request.Files["files"] != null) 
     { 
      using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream)) 
      { 
      var Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image 
      } 
     } 
    } 
+0

가있어. 양식에 다른 내용이 있으면 작동합니까? 업로드 된 이미지를 양식 자체에 표시하려고합니다. – BPX

+0

예, 작동합니다 ... 전체 양식을 보낼 수 있습니다. 단지'FormData'에서 데이터를 추가하면 작동합니다. – Nilesh

+0

업로드하기 전에 파일 이름을 변경할 수 있습니까? 어떻게 업로드 할 특정 경로를 지정할 수 있습니까? – BPX

2

업로드 파일은 매우 간단합니다. 우리는 multipart/form-data와 파일 입력 컨트롤로 설정된 인코딩 타입을 갖는 html 폼이 필요합니다.

보기 : NewProduct.cshtml

<form method="post" enctype="multipart/form-data"> 
    <fieldset> 
     <legend>New Product</legend> 
    <div> 
       <label>Product Name:</label> 
       @Html.TextBoxFor(x => x.ProductName) 
    </div> 
    <div> 
       <label>Product Image:</label> 
       <input name="photo" id="photo" type="file"> 
    </div> 
    <div> 
       @Html.ValidationSummary() 
    </div> 
    <input type="submit" value="Save" /> 
    </fieldset> 
</form> 

는 업로드 된 파일은 HttpFileCollectionBase Request.Files의에서 사용할 수 있습니다.

컨트롤러 :

[HttpPost] 
    public ActionResult NewProduct() 
    { 
     HttpPostedFileBase image = Request.Files["photo"]; 
     if (ModelState.IsValid) 
      { 

       if (image != null && image.ContentLength > 0) 
       { 
        var fileName = Path.GetFileName(image.FileName); 
        string subPath = Server.MapPath("ProductLogo"); 
        bool isExists = System.IO.Directory.Exists(subPath); 
        if (!isExists) 
        System.IO.Directory.CreateDirectory(subPath); 
        var path = Path.Combine(subPath+"\\", fileName); 
        if (System.IO.File.Exists(path)) 
        { 
         var nfile = DateTime.Now.ToString() + "_" + fileName; 
         path = Path.Combine(subPath+"\\", nfile); 

        } 
        file.SaveAs(path); 
        return RedirectToAction("List", "Product"); 
       } 
       else 
       { 
        ModelState.AddModelError("", "Please Select an image"); 
        return View(); 
       } 
      } 
      else 
      {   
      return View(); 
      } 
     } 
+0

OP가 요청한대로 JSON을 사용하지 않습니다 ... 표준 파일 게시판입니다. –

관련 문제