سؤال

هل يوجد HTMLHelper لتحميل الملف؟ على وجه التحديد ، أبحث عن استبدال

<input type="file"/>

باستخدام ASP.NET MVC HTMLHELPER.

أو ، إذا استخدمت

using (Html.BeginForm()) 

ما هو عنصر تحكم HTML لتحميل الملف؟

هل كانت مفيدة؟

المحلول

HTML تحميل ملف ASP MVC 3.

نموذج: (لاحظ أن FileStensionsAttribute متاح في MVCFUtures. سوف التحقق من صحة ملحقات الملف جانب العميل وجانب الخادم.)

public class ViewModel
{
    [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", 
             ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
    public HttpPostedFileBase File { get; set; }
}

عرض HTML:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })
    @Html.ValidationMessageFor(m => m.File)
}

عمل تحكم:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // Use your file here
        using (MemoryStream memoryStream = new MemoryStream())
        {
            model.File.InputStream.CopyTo(memoryStream);
        }
    }
}

نصائح أخرى

تستطيع ايضا استخذام:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

كان لدي نفس السؤال منذ فترة وجادت أحد مشاركات سكوت هانسلمان:

تنفيذ تحميل ملف HTTP مع ASP.NET MVC بما في ذلك الاختبارات والسخرية

أتمنى أن يساعدك هذا.

أو يمكنك أن تفعل ذلك بشكل صحيح:

في فئة تمديد HTMLHelper الخاصة بك:

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return helper.FileFor(expression, null);
    }

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var builder = new TagBuilder("input");

        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        builder.GenerateId(id);
        builder.MergeAttribute("name", id);
        builder.MergeAttribute("type", "file");

        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        // Render tag
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

هذا الخط:

var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

يولد معرف فريد للنموذج ، كما تعلمون في القوائم والأشياء. النموذج [0] .NAME وما إلى ذلك

قم بإنشاء الخاصية الصحيحة في النموذج:

public HttpPostedFileBase NewFile { get; set; }

ثم تحتاج إلى التأكد من أن النموذج الخاص بك سيرسل الملفات:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

ثم ها هو مساعدك:

@Html.FileFor(x => x.NewFile)

نسخة محسنة من إجابة باوليوس زاليدوونيس:

من أجل جعل التحقق من الصحة يعمل بشكل صحيح ، اضطررت إلى تغيير النموذج إلى:

public class ViewModel
{
      public HttpPostedFileBase File { get; set; }

        [Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
        public string FileName
        {
            get
            {
                if (File != null)
                    return File.FileName;
                else
                    return String.Empty;
            }
        }
}

ومنظر إلى:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })
    @Html.ValidationMessageFor(m => m.FileName)
}

هذا مطلوب لأن ما كتبه Serj Sagan حول سمة Filextension تعمل فقط مع السلاسل.

ليستخدم BeginForm, ، ها هي الطريقة لاستخدامها:

 using(Html.BeginForm("uploadfiles", 
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})

هذا يعمل أيضًا:

نموذج:

public class ViewModel
{         
    public HttpPostedFileBase File{ get; set; }
}

رأي:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })       
}

عمل وحدة التحكم:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        var postedFile = Request.Files["File"];

       // now you can get and validate the file type:
        var isFileSupported= IsFileSupported(postedFile);

    }
}

public bool IsFileSupported(HttpPostedFileBase file)
            {
                var isSupported = false;

                switch (file.ContentType)
                {

                    case ("image/gif"):
                        isSupported = true;
                        break;

                    case ("image/jpeg"):
                        isSupported = true;
                        break;

                    case ("image/png"):
                        isSupported = true;
                        break;


                    case ("audio/mp3"):  
                        isSupported = true;
                        break;

                    case ("audio/wav"):  
                        isSupported = true;
                        break;                                 
                }

                return isSupported;
            }

قائمة أنواع المحتوى

أعتقد أن هذا هو الاختراق قليلاً ، لكنه يؤدي إلى تطبيق سمات التحقق الصحيحة وما إلى ذلك

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top