2011-01-24 23 views
91

Mam przesyłanie formularzy, które działa, ale chciałbym przekazać informacje o modelu dla mojej bazy danych, aby zapisać plik pod inną nazwą.Przesyłanie pliku MVC 3 i modelowanie

Oto mój widok 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" /> 
} 

Oto moja Kontroler:

[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"); 
} 

Informacje model nie przepuszcza do sterownika. Czytałem, że być może będę musiał zaktualizować model, jak to zrobić?

+2

Patrz http://stackoverflow.com/questions/9411563/asp-net-mvc3-razor-file-upload-gives-zero -as-file-count dla powiązanego problemu – Lijo

Odpowiedz

124

Formularz nie zawiera żadnych zmiennych wejściowych innych niż plik, więc w działaniu kontrolera nie można oczekiwać niczego innego niż przesłany plik (to wszystko, co jest wysyłane na serwer).Jednym ze sposobów na osiągnięcie tego celu jest włączenie ukrytego znacznika zawierającego identyfikator modelu, który pozwoli ci pobrać go z magazynu danych wewnątrz działania kontrolera, do którego publikujesz (użyj tego, jeśli użytkownik nie powinien modyfikować modelu, ale wystarczy dołączyć plik):

@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" /> 
} 

a potem w swoim działaniu kontrolera:

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

z drugiej strony, jeśli chcesz zezwolić użytkownikowi na zmianę tego modelu, a następnie trzeba będzie zawierać właściwe pola wejściowe dla każdego pola modelu, które chcesz wysłać na serwer:

@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" /> 
} 

a następnie trzeba będzie domyślnym modelem spoiwo zrekonstruować ten model z wniosku:

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

Dziękuję bardzo, działa wspaniale. Francis – Francis

+1

Otrzymuję 'file' jako' null' oraz 'Request.Files.Count' też jest 0, czy byłaby jakakolwiek różnica, jeśli' form' jest 'AjaxForm' i czy istnieją również' routeValues'? – bjan

6

Jeśli nie zawsze mają zdjęć delegowania do działania, można zrobić coś takiego:

[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

rozwiązać

model

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

Controller

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

i widok

@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" /> 
} 

Uwaga tytuł parametru z akcji kontrolera musi się zgadzać z nazwą elementów wejściowych IEnumerable<HttpPostedFileBase> fileUpload ->name="fileUpload[0]"

fileUpload musi pasować

+2

To rozwiązanie jest jedynym rozwiązaniem, które znalazłem dla wielu plików. Dziękujemy za udostępnienie Twojego kodu. –

1

Dla wielu plików; Uwaga nowszą "wielokrotność" atrybut wejściowe:

Postać:

@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" /> 
} 

Kontroler:

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

1st pobrać plik poniżej jquery.form.js url

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

Writ e poniżej kod w 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> 

metoda działania: -

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) 
      { 

      } 
     } 
Powiązane problemy