web-dev-qa-db-ja.com

MVC 4かみそりファイルのアップロード

私はMVC 4に不慣れで、私は私のウェブサイトにFile Upload Controlを実装しようとしています。私は間違いを見つけることができません。私は自分のファイルでnull値を取得しています。

コントローラ:

public class UploadController : BaseController
    {
        public ActionResult UploadDocument()
        {
            return View();
        }

       [HttpPost]
       public ActionResult Upload(HttpPostedFileBase file)
       {
           if (file != null && file.ContentLength > 0)
           {
               var fileName = Path.GetFileName(file.FileName);
               var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
               file.SaveAs(path);
           }

           return RedirectToAction("UploadDocument");
        }
    }

見る:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <input type="file" name="FileUpload" />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
}
233
user2028367

UploadメソッドのHttpPostedFileBaseパラメータは、file inputと同じ名前でなければなりません。

それで、単に入力をこれに変えてください:

<input type="file" name="file" />

また、ファイルはRequest.Filesにあります。

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }
306
Cristi Pufu

それを明確にします。モデル:

public class ContactUsModel
{
    public string FirstName { get; set; }             
    public string LastName { get; set; }              
    public string Email { get; set; }                 
    public string Phone { get; set; }                 
    public HttpPostedFileBase attachment { get; set; }

アクション後

public virtual ActionResult ContactUs(ContactUsModel Model)
{
 if (Model.attachment.HasFile())
 {
   //save the file

   //Send it as an attachment 
    Attachment messageAttachment = new Attachment(Model.attachment.InputStream,       Model.attachment.FileName);
  }
}

最後にhasFileをチェックするためのExtensionメソッド

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AtlanticCMS.Web.Common
{
     public static class ExtensionMethods 
     {
         public static bool HasFile(this HttpPostedFileBase file)
         {
             return file != null && file.ContentLength > 0;
         }        
     }
 }
63
Bishoy Hanna

ページを見る

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

スクリプトファイル

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

コントローラー内

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }
17
Jagadisha B S

パラメータと入力フィールド名に同じ名前が必要なので、入力フィールドの名前を変更するだけで済みます。コードは正常に機能しています。

 <input type="file" name="file" />
6
Hafiz Asad

私は、より良い方法はあなたのコントローラやAPIで HttpPostedFileBase を使うことだと思います。この後は、サイズ、タイプなどを簡単に検出できます。

あなたがここで見つけることができるファイル特性:

MVC3 HttpPostedFileBaseが画像かどうかを調べる方法

例えばImageApi:

[HttpPost]
[Route("api/image")]  
public ActionResult Index(HttpPostedFileBase file)  
{  
    if (file != null && file.ContentLength > 0)  
        try 
        {  
            string path = Path.Combine(Server.MapPath("~/Images"),  
               Path.GetFileName(file.FileName));

            file.SaveAs(path);  
            ViewBag.Message = "Your message for success";  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = "ERROR:" + ex.Message.ToString();  
        }  
    else 
    {  
        ViewBag.Message = "Please select file";  
    }  
    return View();  
}

お役に立てば幸いです。

2
Petr Tomášek