成功附加文件后的CKEditor响应回调

时间:2016-06-20 12:56:28

标签: javascript jquery asp.net-mvc ckeditor ckeditor4.x

使用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期待什么?另外,无论如何我可以上传多个文件吗?

1 个答案:

答案 0 :(得分:0)

这就是我现在返回响应并呈现附件的方法。希望将来可能对某人有所帮助。

[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();
      });
    }
  }
});