MVC项目下 Telerik Upload 的使用方法
1.右键项目然后选择管理NuGet程序包,点击联机 搜索 TelerikMvcExtensions 安装即可(或者点击程序包管理控制器 输入 Install-Package TelerikMvcExtensions)
2.安装成功后,在Content和Scripts 两个文件夹里面都会增加一个Telerik的文件夹,这个文件夹的名字是安装的程序包版本号
3.在layout文件添加 @using Telerik.Web.Mvc.UI 然后在header标签里面加入
@Html.Telerik().StyleSheetRegistrar().DefaultGroup(group => group.DefaultPath("~/Content/2013.2.611").Add("telerik.common.css").Add("telerik.metro.css").Combined(true).Compress(true))
@Html.Telerik().ScriptRegistrar().DefaultGroup(group => group.Combined(true).Compress(true))
把插件的CSS和JS引用进来(这里要注意 插件的JS引用必须要在 Jquery的后面)
4.在view里面也得添加 @using Telerik.Web.Mvc.UI 然后插件的用法是
@(Html.Telerik().Upload()
.Name("attachments")
.Async(async => async
.Save("Save", "Upload")
.Remove("Remove", "Upload")).ClientEvents(events =>
{
events.OnSelect("onSelect");
events.OnSuccess("onSuccess");
})
)
上面的Save 和 Remove调用了 UPloadController的Save(),Remove()方法,而ClientEvents则是调用JS事件
下面是Controller
public class UploadController : Controller
{
//
// GET: /Upload/
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
// The Name of the Upload component is "attachments"
string path = "";
foreach (var file in attachments)
{
// Some browsers send file names with full path. This needs to be stripped.
var fileName = Path.GetFileName(file.FileName);
string p = Server.MapPath("~/UpLoad");
if (!System.IO.Directory.Exists(p))
{
System.IO.Directory.CreateDirectory(p);
}
var physicalPath = Path.Combine(p, fileName);
path = physicalPath;
// The files are not actually saved in this demo
file.SaveAs(physicalPath);
}
// Return an empty string to signify success
return Json(new { url = path }, "text/plain");
}
public ActionResult Remove(string[] fileNames)
{
// The parameter of the Remove action must be called "fileNames"
foreach (var fullName in fileNames)
{
var fileName = Path.GetFileName(fullName);
var physicalPath = Path.Combine(Server.MapPath("~/UpLoad"), fileName);
// TODO: Verify user permissions
if (System.IO.File.Exists(physicalPath))
{
// The files are not actually removed in this demo
System.IO.File.Delete(physicalPath);
}
}
// Return an empty string to signify success
return Content("");
}
}