2013-09-25 2 views
1

내 MVC에서, 나는보기가 하나의 파일 업로드 컨트롤과 하나의 버튼이 포함되어 있습니다.업로드 된 파일을 자바 스크립트에서 MVC로 컨트롤러로 전송하는 방법은 무엇입니까?

<input type="file" id="Uploadfile" /> 
<input type="button" onclick()="GetFile();/> 

자바 스크립트 함수는 I/전달 MVC에서 컨트롤러에 제어 파일 업로드를 통해 선택된 파일을 전송해야

function GetFile() 
    { 
     var file_data = $("#Uploadfile").prop("files")[0]; 
     window.location.href="Calculation/Final?files="+file_data; 
    } 

다음과 같다. 내가

public ActionResult Final(HttpPostedFileBase files) 
    { 
    //here i have got the files value is null. 
    } 

방법 선택한 파일을 가져 와서는 컨트롤러에 보낼 수있는 컨트롤러가? Plz이 문제를 해결할 수 있도록 도와주세요.

+1

파일 전체 포스트 백없이 업로드 할 수 없습니다. –

+0

http://stackoverflow.com/questions/18440220/how-to-upload-file-in-strong-type-view-in-asp-net-mvc/18441187#18441187 –

+0

@ 재스퍼 : 시도해 보셨습니까? –

답변

2

파일 내용을 자바 스크립트를 통해 보낼 수 없습니다 (HTM15 제외). 너는 완전히 잘못하고있다. FileReader API를 통해 HTML5 기반 솔루션을 원할 경우이 것을 확인해야합니다.

FileReader Api 단지 폼 태그 넣고 컨트롤러 후

@using(Html.BeginForm("yourAction","YourControl",FormMethod.Post)) 
{ 
<input type="file" id="fileUpload" /> 
} 

결합 모델을 수행하도록 제어 동작에서의 입력과 동일한 이름을 사용한다.

[HTTPPost] 
public ActionResult Final(HttpPostedFileBase fileUpload) 
    { 
    //here i have got the files value is null. 
    } 
+0

HTML5 FileReader API가 아래의 IE9에서 작동하지 않습니다. –

0

라비의 대답에서 완료, 나는 다음과 같은 using 문을 사용하는 것이 좋습니다 것입니다 :

@using(Html.BeginForm("yourAction","YourControl",FormMethod.Post, new { enctype="multipart/form-data" })) 
{ 
    <input type="file" id="fileUpload" /> 
} 
0

당신은 볼 수 JSON 데이터를 사용하여 작업을 수행 할 수 있습니다. 예로서

,

컨트롤러

public ActionResult Products(string categoryid) 
{ 
List<catProducts> lst = bindProducts(categoryid); 
return View(lst); 
} 
public JsonResult Productsview(string categoryid) 
{ 
//write your logic 
var Data = new { ok = true, catid = categoryid}; 
return Json(Data, JsonRequestBehavior.AllowGet); 
} 

보기 : 아약스 파일 업로드의 환상을 줄 것이다 숨겨진 형태로 전체 포스트 백을 수행하는 코드 아래

@{ 
ViewBag.Title = "Index"; 
} 

@model ASP.NETMVC.Controllers.Categories 

<h2>List Of Categories</h2> 

@Html.ListBox("lst_categories", (IEnumerable<SelectListItem>) ViewBag.Categories) 


<script type="text/javascript"> 
$(function() { 

$('#lst_categories').change(function() { 

var catid = $('#lst_categories :selected').val(); 

$.ajax({ 
url: '@Url.Action("Productsview", "Jquery")', 
type: 'GET', 
dataType: 'json', 
data: { categoryid: catid }, 
cache: false, 

success: function (Data) { 
if (Data.ok) { 

var link = "@Url.Action("Products", "Jquery", new { categoryid = "catid" })"; 
link = link.replace("catid", Data.catid); 
alert(link); 
window.location.href = link; 
} 
} 
}); 
}); 
}); 
</script> 
0

. 그것을 시도

업데이트 :

JS

function Upload(sender) { 
    var iframe = $("<iframe>").hide(); 
    var newForm = $("<FORM>"); 
    newForm.attr({ method: "POST", enctype: "multipart/form-data", action: "/ControllerName/Final" });   
    var $this = $(sender), $clone = $this.clone(); 
    $this.after($clone).appendTo($(newForm)); 
    iframe.appendTo($("html")).contents().find('body').html($(newForm)); 
    newForm.submit(); 
} 

HTML

<input type="file" id="Uploadfile" name="Uploadfile" /> 
<input type="button" onclick="Upload($('#UploadFile'));/> 

컨트롤러

public ActionResult Final(HttpPostedFileBase Uploadfile) 
{ 
    //here i have got the files value is null. 
} 
+0

컨트롤러 동작을 호출하지 않습니다. @Jitendra Pancholi –

+0

예. 너 시도하지 않았 니? –

+0

@ JasperManickaraj : 광산마다 html을 업데이트하고 j를 올바르게 붙여 넣었습니까? –

5

내 프로젝트에서 제공하는 기능이 비슷했습니다. 작업 코드는 다음과 같이 보입니다 :

컨트롤러 클래스

[HttpPost] 
public ActionResult UploadFile(YourModel model1) 
{ 
    foreach (string file in Request.Files) 
    { 
     HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; 
     if (hpf.ContentLength > 0) 
     { 
      string folderPath = Server.MapPath("~/ServerFolderPath"); 
      Directory.CreateDirectory(folderPath); 

      string savedFileName = Server.MapPath("~/ServerFolderPath/" + hpf.FileName); 
      hpf.SaveAs(savedFileName); 
      return Content("File Uploaded Successfully"); 
     } 
     else 
     { 
      return Content("Invalid File"); 
     } 
     model1.Image = "~/ServerFolderPath/" + hpf.FileName; 
    } 

    //Refactor the code as per your need 
    return View(); 
} 

보기

@using (@Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
<table style="border: solid thin; margin: 10px 10px 10px 10px"> 
    <tr style="margin-top: 10px"> 
     <td> 
      @Html.Label("Select a File to Upload") 
      <br /> 
      <br /> 
      <input type="file" name="myfile"> 
      <input type="submit" value="Upload" /> 
     </td> 
    </tr> 
</table> 
} 
관련 문제