2011-01-24 37 views
91

Tôi có tải lên biểu mẫu hoạt động nhưng tôi muốn chuyển thông tin mô hình cho cơ sở dữ liệu của mình để lưu tệp có tên khác của khóa học.MVC 3 tải lên tệp và mô hình ràng buộc

Đây là quan điểm của tôi Razor:

@model CertispecWeb.Models.Container 

@{ 
    ViewBag.Title = "AddDocuments"; 
} 

<h2>AddDocuments</h2> 

@Model.ContainerNo 

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, 
      new { enctype = "multipart/form-data" })) 
{ 
    <input type='file' name='file' id='file' /> 
    <input type="submit" value="submit" /> 
} 

Đây là điều khiển của tôi:

[HttpPost] 
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file) 
{ 
    if (file.ContentLength > 0) 
    { 
     var fileName = Path.GetFileName(file.FileName); 
     var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), 
         containers.ContainerNo); 
     file.SaveAs(path); 
    } 

    return RedirectToAction("Index"); 
} 

Các thông tin mô hình không được truyền thông qua bộ điều khiển. Tôi đã đọc rằng tôi có thể cần phải cập nhật mô hình, làm thế nào tôi sẽ làm điều này?

+2

Tham khảo http://stackoverflow.com/questions/9411563/asp-net-mvc3-razor-file-upload-gives-zero -as-file-count cho một vấn đề liên quan – Lijo

Trả lời

124

Biểu mẫu của bạn không chứa bất kỳ thẻ đầu vào nào khác ngoài tệp trong hành động điều khiển của bạn, bạn không thể mong nhận bất kỳ thứ gì khác ngoài tệp được tải lên (đó là tất cả những gì được gửi tới máy chủ).Một cách để đạt được điều này là bao gồm một thẻ ẩn chứa id của mô hình cho phép bạn lấy nó từ kho dữ liệu của bạn bên trong hành động điều khiển mà bạn đang đăng lên (sử dụng điều này nếu người dùng không được sửa đổi mô hình nhưng chỉ cần đính kèm một tập tin):

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.HiddenFor(x => x.Id) 
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="submit" /> 
} 

và sau đó trong hành động điều khiển của bạn:

[HttpPost] 
public ActionResult Uploadfile(int id, HttpPostedFileBase file) 
{ 
    Containers containers = Repository.GetContainers(id); 
    ... 
} 

Mặt khác nếu bạn muốn cho phép người dùng chỉnh sửa mô hình này sau đó bạn sẽ cần phải bao gồm các hợp các trường nhập cho mỗi trường của mô hình mà bạn muốn gửi đến máy chủ:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.TextBoxFor(x => x.Prop1) 
    @Html.TextBoxFor(x => x.Prop2) 
    @Html.TextBoxFor(x => x.Prop3) 
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="submit" /> 
} 

và sau đó bạn sẽ có mô hình binder mặc định tái tạo lại mô hình này từ yêu cầu:

[HttpPost] 
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file) 
{ 
    ... 
} 
+4

Cảm ơn bạn rất nhiều, công trình tuyệt vời. Francis – Francis

+1

Tôi nhận được 'tập tin' như' null' và 'Request.Files.Count' là 0 quá, sẽ có bất kỳ sự khác biệt nếu' form' là một 'AjaxForm' và có' routeValues' là tốt? – bjan

6

Nếu bạn không phải lúc nào có hình ảnh gửi bài đến hành động của bạn, bạn có thể làm một cái gì đó như thế này:

[HttpPost] 
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{ 
    //do container stuff 

    if (Request.Files != null) 
    { 
     foreach (string requestFile in Request.Files) 
     { 
      HttpPostedFileBase file = Request.Files[requestFile]; 
      if (file.ContentLength > 0) 
      { 
       string fileName = Path.GetFileName(file.FileName); 
       string directory = Server.MapPath("~/App_Data/uploads/"); 
       if (!Directory.Exists(directory)) 
       { 
        Directory.CreateDirectory(directory); 
       } 
       string path = Path.Combine(directory, fileName); 
       file.SaveAs(path); 
      } 
     } 
    } 

} 
8

Giải Quyết

mẫu

public class Book 
{ 
public string Title {get;set;} 
public string Author {get;set;} 
} 

khiển

public class BookController : Controller 
{ 
    [HttpPost] 
    public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload) 
    { 
     throw new NotImplementedException(); 
    } 
} 

Và Xem

@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{  
    @Html.EditorFor(m => m) 

    <input type="file" name="fileUpload[0]" /><br />  
    <input type="file" name="fileUpload[1]" /><br />  
    <input type="file" name="fileUpload[2]" /><br />  

    <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" /> 
} 

Chú ý tiêu đề của tham số từ controller action phải phù hợp với tên của các yếu tố đầu vào IEnumerable<HttpPostedFileBase> fileUpload ->name="fileUpload[0]"

fileUpload phải phù hợp

+2

Giải pháp này là giải pháp duy nhất tôi tìm thấy cho nhiều tệp. Cảm ơn bạn đã chia sẻ mã của mình. –

1

Đối với nhiều tệp; lưu ý các phiên bản mới hơn "nhiều" thuộc tính cho đầu vào:

Mẫu:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"})) 
{ 
    <label for="files">Filename:</label> 
    <input type="file" name="files" multiple="true" id="files" /> 
    <input type="submit" /> 
} 

Bộ điều khiển:

[HttpPost] 
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files) 
{ 
    return View(); 
} 
1

1st tải jquery.form.js tập tin từ bên dưới url

http://plugins.jquery.com/form/

Writ e bên dưới mã trong cshtml

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" })) 
{ 
    <div id="uploadTemplate"> 

     <input type="text" value="Asif" id="txtname" name="txtName" /> 


     <div id="dvAddTemplate"> 
      Add Template 
      <br /> 
      <input type="file" name="file" id="file" tabindex="2" /> 
      <br /> 
      <input type="submit" value="Submit" /> 
      <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" /> 
     </div> 

     <div id="TemplateTree" style="overflow-x: auto;"></div> 
    </div> 

    <div id="progressBarDiv" style="display: none;"> 
     <img id="loading-image" src="~/Images/progress-loader.gif" /> 
    </div> 

} 


<script type="text/javascript"> 

    $(document).ready(function() { 
     debugger; 
     alert('sample'); 
     var status = $('#status'); 
     $('#frmTemplateUpload').ajaxForm({ 
      beforeSend: function() { 
       if ($("#file").val() != "") { 
        //$("#uploadTemplate").hide(); 
        $("#btnAction").hide(); 
        $("#progressBarDiv").show(); 
        //progress_run_id = setInterval(progress, 300); 
       } 
       status.empty(); 
      }, 
      success: function() { 
       showTemplateManager(); 
      }, 
      complete: function (xhr) { 
       if ($("#file").val() != "") { 
        var millisecondsToWait = 500; 
        setTimeout(function() { 
         //clearInterval(progress_run_id); 
         $("#uploadTemplate").show(); 
         $("#btnAction").show(); 
         $("#progressBarDiv").hide(); 
        }, millisecondsToWait); 
       } 
       status.html(xhr.responseText); 
      } 
     }); 

    }); 


</script> 

phương pháp hành động: -

public ActionResult Index() 
     { 
      ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

      return View(); 
     } 

public void Upload(HttpPostedFileBase file, string txtname) 
     { 

      try 
      { 
       string attachmentFilePath = file.FileName; 
       string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1); 

      } 
      catch (Exception ex) 
      { 

      } 
     } 
Các vấn đề liên quan