【问题标题】:File upload with grails and jquery使用 grails 和 jquery 上传文件
【发布时间】:2023-03-21 13:22:01
【问题描述】:

我有一个包含多个输入的表单以及一个 doc 或 pdf 文件上传。

//Multiple input fields are here then upload ->
<div class="controls">
    <div class="fileupload ${ person?.attachment ? 'fileupload-exists' : 'fileupload-new' }" id="attachment" data-provides="fileupload" data-name="attachment">
        <span class="btn btn-file">
            <span class="fileupload-new">Add</span>
            <span class="fileupload-exists">Change</span>
            <input type="file" />
        </span>
        <span class="fileupload-preview"></span>
        <a href="#" class="close fileupload-exists" data-dismiss="fileupload" style="float: none">×</a>
    </div>
</div>

并且表单是用jquery提交的

$(document).on('click', "#submit", function () {
    //TODO Take the chosen file and upload it with form data
    //Taking data from form and contructing a object and posting it with ajax
}

当按下#submit 时,我不知道如何使用表单上传 doc/pdf 文件。

客户端上传取自here

我查看了g:formg:uploadForm,但我真的不想使用它们,因为它们似乎会刷新页面和/或重定向用户。

【问题讨论】:

  • 你能在控制器端的参数中获取文件对象吗?
  • 不,我尝试使用$("#attachment").find('input') 发送它,但这只是对象的标题和长度。

标签: jquery grails


【解决方案1】:

使用下面的函数在表单提交时使用 ajax 发送文件 在视图结束时

        function formSubmit(){

           var formData=new FormData($('form#create-form')[0]);
            $.ajax({url: 'createAttachment', type:'POST', data: formData, processData: false,contentType: false,dataType: 'script',success:function(result){

            }});
            return false
        }

在控制器端使用下面的代码来访问文件对象

def createAttachment = {
    List attachmentsFiles=[]
    request.fileNames.each {
        def singleFile = request.getFile(it)
        if(singleFile.getOriginalFilename()) {
            attachmentsFiles.add(singleFile)
        }
    }
    attachmentsFiles.each { file ->
       println(file.getOriginalFilename())
    }
  //put your code here
}

attachmentsFiles 将包含所有上传的文件。

【讨论】:

  • 我的表单有&lt;div class="form-horizontal"&gt;form elements&lt;/div&gt; 没有&lt;form&gt; 标签,所以表单数据在这种情况下不起作用?
  • 您可以简单地创建 FormData() 的对象并将数据附加到它上面var formData =new FormData(); formData.append('file', document.getElementById('file').files[0]);
  • 另一个问题我得到了文件,但其他表单数据不想转换回它的模型。 formData.append('file',document.getElementById('uploadedFile').files[0]); formData.append('person',person); 文件作为多部分到达,人作为通用对象到达
  • 您可以发送该对象的 id formData.append('person',person.id);
  • 哦,太好了!非常感谢。
猜你喜欢
  • 2017-04-10
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 2013-10-09
  • 2018-02-24
相关资源
最近更新 更多