2016-07-04 133 views
0

我正在设计一个带有textarea的表单,它可以插入ajax上传的结果(只是一个[image UUID]标签的字符串)。以便用户可以上传尽可能多的图像(并调整到适当的位置)。jQuery插入ajax上传结果到textarea

这是我目前的工作:

enter image description here

我使用Ajax图像文件上传到服务器,和服务器将存储(图像)文件和回复的[图像UUID]字符串。

而且我希望将[image UUID]字符串自动插入光标所在的#textarea。

上面的图片工作,但越野车和丑陋。

  • 它可以在Safari
  • 但不是在Firefox。它触发AJAX两次,发送重复的文件,我不知道为什么。
  • “上传”按钮远在#textarea下面,对用户来说不直观。
  • 如果我将form2直接移到#textarea下面。它变成嵌入形式。当ajax提交一个文件时,它会触发form2和form1,使form1提交。

窗口2的提交按钮:

<form id="ajaxFileUploadForm" method="post" th:action="@{/user/doAjaxUpload}" enctype="multipart/form-data"> 
    <input type="file" name="ajaxFile" id="ajaxFile" class="btn btn-default"/> 
    <button value="Upload" class="btn btn-default" onclick="uploadJqueryForm()" id="uploadImageButton"> 
    insert image 
    </button> 
</form> 

和JS代码:

<script th:inline="javascript"> 

    (function ($, undefined) { 
     $.fn.getCursorPosition = function() { 
     var el = $(this).get(0); 
     var pos = 0; 
     if ('selectionStart' in el) { 
      pos = el.selectionStart; 
     } else if ('selection' in document) { 
      el.focus(); 
      var Sel = document.selection.createRange(); 
      var SelLength = document.selection.createRange().text.length; 
      Sel.moveStart('character', -el.value.length); 
      pos = Sel.text.length - SelLength; 
     } 
     return pos; 
     } 
    })(jQuery); 

    //using jquery.form.js 
    function uploadJqueryForm() { 
     $('#uploadImageButton').attr('disabled', 'disabled'); 

     $("#ajaxFileUploadForm").ajaxForm({ 
     success: function (data) { 
      console.log(data); 
      var position = $("#textarea").getCursorPosition(); 
      var content = $('#textarea').val(); 
      var newContent = content.substr(0, position) + "\n" + data + "\n" + content.substr(position); 
      $('#textarea').val(newContent); 
      $('#uploadImageButton').removeAttr('disabled'); 
     }, 
     dataType: "text" 
     }).submit(); 
    } 

    </script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.js"></script> 

有没有更好的解决方案,可以使 '上传' 按钮的正下方#textarea,插入服务器回复#textarea(光标的位置),并完美地跨浏览器工作?

非常感谢!

回答

0

另一个解决方案,可以更直观地为您的用户在上传文件或图像的过程中单击文本区域或将图像拖放到textarea中。您可以使用许多插件http://www.dropzonejs.com/

问候。

+0

有没有例子dropzonejs追加结果到#textarea? – smallufo