Обратный вызов ответа CKEditor после успешного прикрепления файла

Использование CKEditor для отправки электронной почты и загрузки вложений. Ниже приведена минимальная конфигурация, которую я получил от this source.

CKEDITOR.replace('email.Message', {
  filebrowserUploadUrl: '/Controller/UploadAttachment',
  extraPlugins: 'attach', // attachment plugin
  toolbar: this.customToolbar, //use custom toolbar
  autoCloseUpload: true, //autoClose attachment container on attachment upload
  validateSize: 30, //30mb size limit
  onAttachmentUpload: function(response) {
    /*
     the following code just utilizes the attachment upload response to generate 
     ticket-attachment on your page
    */
    attachment_id = $(response).attr('data-id');
    if (attachment_id) {
      attachment = $(response).html();
      $closeButton = $('<span class="attachment-close">').text('x').on('click', closeButtonEvent)
      $('.ticket-attachment-container').show()
        .append($('<div>', {
          class: 'ticket-attachment'
        }).html(attachment).append($closeButton))
        .append($('<input>', {
          type: 'hidden',
          name: 'attachment_ids[]'
        }).val(attachment_id));
    }
  }
});

На стороне Controller у меня ниже code

const string scriptTag = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}')</script>";

public ContentResult UploadAttachment() 
{
  string basePath = HttpContext.Server.MapPath("~/assets/Images/");
  const string baseUrl = @"/ckfinder/userfiles/";
  var funcNum = 0;
  int.TryParse(Request["CKEditorFuncNum"], out funcNum);

  if (Request.Files == null || Request.Files.Count < 1)
    return BuildReturnScript(funcNum, null, "No file has been sent");

  if (!System.IO.Directory.Exists(basePath))
    return BuildReturnScript(funcNum, null, "basePath folder doesn't exist");

  var receivedFile = Request.Files[0];

  var fileName = receivedFile.FileName;
  if (string.IsNullOrEmpty(fileName)) {
    return BuildReturnScript(funcNum, null, "File name is empty");
  }

  var sFileName = System.IO.Path.GetFileName(fileName);

  var nameWithFullPath = System.IO.Path.Combine(basePath, sFileName);
  //Note: you may want to consider using your own naming convention for files, as this is vulnerable to overwrites
  //e.g. at the moment if two users uploaded a file called image1.jpg, one would clash with the other.
  //In the past, I've used Guid.NewGuid() combined with the file extension to ensure uniqueness.
  receivedFile.SaveAs(nameWithFullPath);

  var url = baseUrl + sFileName;
  return BuildReturnScript(funcNum, url, null);
}

private ContentResult BuildReturnScript(int functionNumber, string url, string errorMessage) {
  return Content(
    string.Format(scriptTag, functionNumber, HttpUtility.JavaScriptStringEncode(url ? ? ""), HttpUtility.JavaScriptStringEncode(errorMessage ? ? "")),
    "text/html"
  );
}

Ниже приведен ответ, который я получаю внутри onAttachmentUpload - function

<form enctype="multipart/form-data" method="POST" dir="ltr" lang="en" action="/Controller/UploadAttachment?CKEditor=email_Message&amp;CKEditorFuncNum=0&amp;langCode=en">
    <label id="cke_73_label" for="cke_74_fileInput_input" style="display:none"></label>
    <input style="width:100%" id="cke_74_fileInput_input" aria-labelledby="cke_73_label" type="file" name="attachment" size="38">
</form>   
<script>
      window.parent.CKEDITOR.tools.callFunction(98);
      window.onbeforeunload = function({
             window.parent.CKEDITOR.tools.callFunction(99)
      });
</script>

Но он ожидает data-id для вложения id. Я понятия не имею, как должен выглядеть ответ. Может ли кто-нибудь сказать мне, как должен выглядеть фактический ответ и что data-id он ожидает как attr в ответ? Кроме того, я могу в любом случае загрузить несколько файлов с этим?


person Guruprasad J Rao    schedule 20.06.2016    source источник


Ответы (1)


Вот как я сейчас возвращаю ответ и отображаю прикрепленный файл. Надеюсь, это может помочь кому-то в будущем.

[AcceptVerbs(HttpVerbs.Post)]
public ContentResult UploadAttachment() {
  string basePath = HttpContext.Server.MapPath("~/somepath");
  var funcNum = 0;
  int.TryParse(Request["CKEditorFuncNum"], out funcNum);

  if (Request.Files == null || Request.Files.Count < 1)
    return Content("No file has been sent");

  if (!System.IO.Directory.Exists(basePath))
    Directory.CreateDirectory(Path.Combine(basePath));

  var receivedFile = Request.Files[0];

  var fileName = receivedFile.FileName;
  if (string.IsNullOrEmpty(fileName)) {
    return Content("File name is empty");
  }

  var sFileName = System.IO.Path.GetFileName(fileName);

  var nameWithFullPath = Path.Combine(basePath, sFileName);

  receivedFile.SaveAs(nameWithFullPath);
  var content = "<span data-href=\"" + nameWithFullPath + "\" data-id=\"" + funcNum + "\"><i class=\"fa fa-paperclip\"> </i> " + sFileName + "</span>";
  return Content(content);
}

а на стороне JS у меня есть код ниже для добавления имени загруженного файла:

CKEDITOR.replace('email.Message', {
  filebrowserUploadUrl: '/Controller/UploadAttachment',
  extraPlugins: 'attach', // attachment plugin
  toolbar: this.customToolbar, //use custom toolbar
  autoCloseUpload: true, //autoClose attachment container on attachment upload
  validateSize: 30, //30mb size limit
  onAttachmentUpload: function(response) {
    /*
     the following code just utilizes the attachment upload response to generate 
     ticket-attachment on your page
    */
    attachment_id = $(response).attr('data-id');
    if (attachment_id) {
      attachment = response;
      $closeButton = '<span class="attachment-close btn btn-danger float-right" style="margin-top:-7px"><i class="fa fa-trash"></i></span>'; //.on('click', closeButtonEvent)
      $respDiv = '<ol class="breadcrumb navbar-breadcrumb" style="padding:18px 15px"><li style="display:block">' + attachment + $closeButton + '</li></ol>';
      $('.ticket-attachment-container').show()
        .append($('<div>', {
          class: 'ticket-attachment'
        }).html($respDiv))
        .append($('<input>', {
          type: 'hidden',
          name: 'attachment_ids[]'
        }).val(attachment_id));
      $('.ticket-attachment-container').on('click', '.attachment-close', function() {
        $(this).closest('.ticket-attachment').remove();
        if (!$('.ticket-attachment-container .ticket-attachment').length)
          $('.ticket-attachment-container').hide();
      });
    }
  }
});
person Guruprasad J Rao    schedule 21.06.2016