CKEditor 4 Upload Image套件
於head tag事先include ckeditor.js檔
<script src="http://cdn.ckeditor.com/4.5.11/standard-all/ckeditor.js"></script>
注意,一定要Standard-All、Full-All或是利用CKBuilder客制化添加,
並使用 extraPlugins: 'uploadimage' 才可以做到圖片拖拉上傳。
index.cshtml為
<textarea name="editor2"></textarea> @section scripts{ <script> CKEDITOR.replace('editor2', { extraPlugins: 'uploadimage',//表示使用uploadimage套件 uploadUrl: '@Url.Action("UpLoadToDB")' //,filebrowserUploadUrl: '@Url.Action("UpLoadToDB")' + '?type=Files' }); </script> }
要使用Upload Image plugin時需設定以下兩參數
config.extraPlugins = 'uploadimage';
config.UploadUrl = '@Url.Action("UpLoadToDB")';
而如果UploadUrl參數沒設定的話,則設定
config.filebrowserUploadUrl = '@Url.Action("UpLoadToDB")' + '?type=Files'
可暫時替代UploadUrl參數,或是設定imageUploadUrl也可替代UploadUrl參數,
config.imageUploadUrl: '@Url.Action("UpLoadToDB")' + '?type=Files'
Controller為
using System.Web.Mvc;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UpLoadToDB(HttpPostedFileBase upload)
{
return Content(JsonConvert.SerializeObject(SaveFile(upload)), "application/json");
}
private JObject SaveFile(HttpPostedFileBase upload)
{
if (Directory.Exists(Server.MapPath("~/imagefiles")) == false)
{
Directory.CreateDirectory(Server.MapPath("~/imagefiles"));
}
if (System.IO.File.Exists(Path.Combine(Server.MapPath("~/imagefiles"), upload.FileName)))
{
System.IO.File.Delete(Path.Combine(Server.MapPath("~/imagefiles"), upload.FileName));
}
upload.SaveAs(Path.Combine(Server.MapPath("~/imagefiles"), upload.FileName));
//先假設都會上傳成功,uploaded固定為1
JObject obj = new JObject(
new JProperty("uploaded", 1),
new JProperty("fileName", upload.FileName),
new JProperty("url", "/imagefiles/" + upload.FileName)
);
return obj;
}
}
}
後端回傳的設定請參考Server Side Configuration
參考資料: