【问题标题】:How to work with ajax in play framework 2.1.*如何在 play framework 2.1.* 中使用 ajax
【发布时间】:2013-08-28 05:14:26
【问题描述】:

我正在与play framework 2.1.2 合作。我想在play framework 中使用Ajax

我在做什么?我正在上传多个文件,我希望如果用户没有选择要上传的文件,那么我想要一些消息,例如 '你没有选择任何文件' 进行上传如果用户选择要上传的文件并点击上传,我希望收到一些消息,例如文件已上传

我的观点是:

@form(action = routes.upload.up, 'enctype -> "multipart/form-data",'_id->"he") {
            <input type="file" name="file" accept="application/pdf" multiple="multiple"><br/> 
            <input type="submit" id="if" value="upload and extract"> 

            }

并获取数据。

现在当用户点击上传按钮时,如果用户在文件上传后选择要上传的文件,我想打印消息文件已上传,如果用户当时没有选择文件,我想要显示消息选择一个文件

我想发送我将在控制器部分处理文件后发送的消息数据。在那个控制器部分我想发送到那个 Ajax 的消息之后,我会得到什么消息。

控制器部分是:

Http.MultipartFormData body = request().body().asMultipartFormData();
        List<FilePart> resourceFiles = body.getFiles();


        if (!resourceFiles.isEmpty()) {

            for (FilePart upload : resourceFiles) {

                String targetPath = "/home/rahul/Documents/upload/"
                        + upload.getFilename();
                upload.getFile().renameTo(new File(targetPath));
            }
            return ok("File uploaded ");  //i want to print this result as a message 
        } else {
            return forbidden(); 
        }
    }

我浏览了一些代码,但没有得到足够的解决方案。

给我一​​些通过 ajax 的想法。

【问题讨论】:

标签: java ajax json playframework playframework-2.1


【解决方案1】:

几周前,我使用 jquery-file-upload 实现了使用 ajax 上传文件。 我可能会发布我的解决方案,希望您会满意。此示例为简单的 1 文件上传,但可以扩展。

脚本

<script src="@routes.Assets.at("javascripts/jquery-file-upload/jquery.iframe-transport.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/jquery-file-upload/vendor/jquery.ui.widget.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/jquery-file-upload/jquery.fileupload.js")" type="text/javascript"></script>

查看

<input type="file" id="@d" name="@d" data-url="@code.routes.Ext.upload()"  />
<script type="text/javascript">
    $(document).ready(function () {
        $('#@d').fileupload({
            replaceFileInput: true,
            done: function (e, data) {
                //Here you got server response.
                console.log(data);
                var d = data.result;
                alert(d);
                $('#img1').attr("src",d);
            }
        });
    });
</script>

@d 是您的视图参数。

控制器

在您的代码中,您可以使用return ok("File uploaded ") 来响应客户。

完整的源代码可以在here (Scala)hereherehere找到

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多