اذهب إلى المحتوى
  • 0

كيف أستعمل File Upload في ASP.NET MVC 3.0؟

محمد بوسكوري

السؤال

Recommended Posts

  • 0

كما هو معروف، يجب استعمال Input من نوع file ليتم تصفح حاسوبك لاختيار الملف المراد تحميله، وهذا الحقل سيتواجد في View -الجزء V من MVC- ،حيث سيكون في المتحكم Controller الكود المسؤول عن نقل الملف وتخزينه في السيرفر.

أي أن كودView  سيكون كما يلي :

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

والمتحكم Controller :

public class HomeController : Controller
{
    // إظهار الواجهة
    public ActionResult Index()
    {
        return View();
    }

    // تحميل الملف، عن طريق نقله من مكانه إلى المكان المعيّن
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // التأكد من وجود الملف
        if (file != null && file.ContentLength > 0) 
        {
            // تحميل الملف
            var fileName = Path.GetFileName(file.FileName);
            //  ~/App_Data/uploads folder نقل نسخة من الملف إلى
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // نقل المتصفح لإظهار الواجهة من جديد
        return RedirectToAction("Index");        
    }
}

 كما يمكنك أيضا تحميل العديد من الملفات، وذلك عن طريق إضافة عدة حقول من نوع file :

<form action="" method="post" enctype="multipart/form-data">

  <label for="file1">Filename:</label>
  <input type="file" name="files" id="file1" />

  <label for="file2">Filename:</label>
  <input type="file" name="files" id="file2" />

  <input type="submit"  />
</form>http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

ويكون كود تحميل الملفات :

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file in files) {
    if (file.ContentLength > 0) {
      var fileName = Path.GetFileName(file.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
}

Uploading a File (Or Files) With ASP.NET MVC

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...