0

将图像上传到使用 CK-Editor 选择的服务器

动作方法 .Net Core MVC

在此处输入图像描述 在此处输入图像描述

<script src="~/ckeditor/ckeditor.js"></script>


<script>
    CKEDITOR.replace('editor1', {
        customConfig: '/js/CustomConfig.js'
    });


    CKEDITOR.editorConfig = function (config) {
        config.removeDialogTabs = 'image:advanced;image:Link;link:advanced;link:upload';
        config.filebrowserImageUploadUrl = '/Home/Uploads' //Action for Uploding image  
    };

</script>
4

1 回答 1

0

您的上传功能应如下所示。这个对我有用。我建议你也可以参考CKEditor FileUpload Helper。它也应该对你有所帮助。

 [HttpPost]
 public ActionResult UploadImg(IFormFile upload)
 {                  
     if (upload.Length <= 0 ) return null;
     // check the upload file is image
     if (!System.Drawing.Image.FromStream(upload.OpenReadStream()))
     {
         dynamic error= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" pls upload img"\"}}");
         return Json(error);
     }

     var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();

     Image image = Image.FromStream(upload.OpenReadStream());
     int width = image.Width;
     int height = image.Height;
     // limit image size 
     if ((width > 750) || (height > 500))
     {
         var error = "The file size is wrong. ";
         dynamic msg= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + error + "\"}}");
         return Json(msg);
     }
     // file size limit, 500k
     if (upload.Length > 500 * 1024)
     {
         var error= "file is too large";
         dynamic msg= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + error+ "\"}}");
         return Json(msg);                
     }

     var path = Path.Combine(
            Directory.GetCurrentDirectory(), "wwwroot/images/CKEditorImages",
            fileName);

     using (var stream = new FileStream(path, FileMode.Create))
     {
         upload.CopyTo(stream);

     }

     var url = $"{"/images/CKEditorImages/"}{fileName}";
     var successMessage = "upload successfully";
     dynamic success = JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}");
     return Json(success);
 }
于 2021-07-23T09:35:50.033 回答