2015-12-31 70 views
0

我試圖上傳一個文件並附上一些模型信息。 在我的表格中,我已經有一個字段'圖像'(字符串)來保存圖像的相對URL。EF7 MVC ASP.NET文件上傳形式

但我真的不知道如何做上傳本身。 我已經閱讀了很多教程,但他們都使用HttpPostedFileBase,不再支持?

這是我迄今:

上傳頁面:

@using (Html.BeginForm("Lets", "Create", FormMethod.Post, new { @enctype = "multipart/form-data" })) 
      { 
       @Html.AntiForgeryToken() 
       <fieldset> 
        <div class="form-group"> 
         <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield"> 
          @Html.LabelFor(m => m.Lets.Name, new { @class="mdl-textfield__label" }) 
          @Html.TextBoxFor(m => m.Lets.Name, new { @class= "form-control mdl-textfield__input" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield"> 
          @Html.LabelFor(m => m.Lets.Images) 
          <input type="file" name="LetsImages" id="m.Lets.Images" /> <br /> 
         </div> 
        </div> 
        <div class="form-group"> 
         <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield"> 
          @Html.LabelFor(m => m.Lets.Description, new { @class="mdl-textfield__label" }) 
          @Html.TextBoxFor(m => m.Lets.Description, new { @class= "form-control mdl-textfield__input" }) 
         </div> 
        </div> 
        <div class="form-group"> 
         <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield"> 
          @Html.LabelFor(m => m.Lets.Credits, new { @class="mdl-textfield__label" }) 
          @Html.TextBoxFor(m => m.Lets.Credits, new { @class= "form-control mdl-textfield__input" }) 
         </div> 
        </div> 
        <div class="form-group"> 
         <div class="mdl-cell col-md-10"> 
          @Html.LabelFor(m => m.Lets.Group) 
          @Html.DropDownListFor(m => m.Lets.GroupId, new SelectList(Model.Groups, "Id", "Name"), "-- Selecteer een Groep --", new { @class= "form-control" }) 
         </div> 
        </div> 
        @Html.ActionLink("Terug naar het overzicht", "Index", new { }, new { @class= "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" }) 
        <input type="submit" value="Save" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" /> 
       </fieldset> 
      } 

控制器:

[HttpGet] 
    public IActionResult Create() 
    { 
     var model = new LetsViewModel 
     { 
      Lets = new Lets(), 
      Groups = _kletsContext.Groups.AsEnumerable(), 
      Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name) 
     }; 

     return View(model); 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public IActionResult Create(LetsViewModel model) 
    { 
     LetsViewModel viewModel = null; 
     try 
     { 
      if(!ModelState.IsValid) 
       throw new Exception("The Lets model is not valid!"); 

       var letsImage = "INSERT LOGIC FOR IMAGEUPLOAD HERE?"; 
       model.Lets.UserId = User.GetUserId(); 
       model.Lets.StatusId = 1; 
       model.Lets.Images = letsImage; 


      _kletsContext.Lets.Add(model.Lets); 
      if (_kletsContext.SaveChanges() == 0) 
      { 
       throw new Exception("The Lets model could not be saved!"); 
      } 

      //Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true); 

     return RedirectToAction("Index", "Home"); 

     } 
     catch(Exception ex) 
     { 
      ModelState.AddModelError(string.Empty, "Unable to save changes."); 

      viewModel = new LetsViewModel 
      { 
       Lets = model.Lets, 
       Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name) 
      }; 
     } 
     return View(viewModel); 
    } 

我加,我覺得邏輯應該來的地方嗎?

所以我想要做的是:

上傳圖片到一個文件夾重命名 它 Store中的相對路徑作爲一個字符串的分貝。

謝謝

回答

1

有一個在MVC6沒有HttpPostedFileBase,你必須使用IFormFile這樣的:

public FileDetails UploadSingle(IFormFile file) 
{ 
    FileDetails fileDetails; 
    using (var reader = new StreamReader(file.OpenReadStream())) 
    { 
     var fileContent = reader.ReadToEnd(); 
     var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition); 
     fileDetails = new FileDetails 
     { 
      Filename = parsedContentDisposition.FileName, 
      Content = fileContent 
     }; 
    } 

    return fileDetails; 
} 
0

可以使用處理程序上傳圖片,鏈接教程

http://www.c-sharpcorner.com/blogs/uploading-files-using-jquery-ajax-in-asp-net1

http://www.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx

http://www.dotnetjalps.com/2011/12/async-file-upload-with-jquery-and.html?m=1

這些教程使用jquery將圖像傳遞給處理程序,然後處理程序將圖像保存到文件夾中。您可以在上載到文件夾之前重命名圖像,然後取回保存的圖像名稱作爲響應,然後將圖像名稱與其他模型屬性一起保存。

0

我終於得到了它的工作:

  1. 包括使用Microsoft.AspNet.Hosting;using System.IO; using System.Net.Http.Headers;
  2. 添加public IHostingEnvironment _environment { get; set;} 到控制器(我把它添加到我的commoncontroller,然後它提供給我,我的控制器上)
  3. 然後在我創建:

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public IActionResult Create(LetsViewModel model, IFormFile LetsImages) 
    { 
        LetsViewModel viewModel = null; 
        try 
        { 
         if(!ModelState.IsValid) 
          throw new Exception("The Lets model is not valid!"); 
    
          if(LetsImages != null) 
          { 
            var targetDirectory = Path.Combine(_environment.WebRootPath, string.Format("images/uploads")); 
            var fileName = ContentDispositionHeaderValue 
            .Parse(LetsImages.ContentDisposition) 
            .FileName 
            .Trim('"'); 
            var savePath = Path.Combine(targetDirectory, fileName); 
            var relPath = "/images/uploads/" + fileName; 
            try 
            { 
             LetsImages.SaveAs(savePath); 
             model.Lets.Images = relPath; 
            } 
            catch 
            { 
             throw new Exception("There was a problem with saving the file!"); 
            } 
          } 
          else 
          { 
           model.Lets.Images = null; 
          } 
          model.Lets.UserId = User.GetUserId(); 
          model.Lets.StatusId = 1; 
    
    
         _kletsContext.Lets.Add(model.Lets); 
         if (_kletsContext.SaveChanges() == 0) 
         { 
          throw new Exception("The Lets model could not be saved!"); 
         } 
    
         //Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true); 
    
        return RedirectToAction("Index", "Home"); 
    
        } 
        catch(Exception ex) 
        { 
         ModelState.AddModelError(string.Empty, "Unable to save changes."); 
    
         viewModel = new LetsViewModel 
         { 
          Lets = model.Lets, 
          Groups = _kletsContext.Groups.AsEnumerable(), 
          Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name) 
         }; 
        } 
        return View(viewModel); 
    } 
    

只要確保你已經創建了圖像應該屬於的文件夾,否則它不會沒有任何錯誤的工作!

謝謝大家的幫助!