PlayFramework:Ajax + Drag n'Drop + File Upload + File对象在控制器中?

Jas*_*zek 15 ajax drag-and-drop file-upload playframework

有没有人知道通过Ajax上传文件并使用支持PlayFramework将文件上传转换为File对象的桌面拖放的方法?

我尝试了几种不同的方法,没有任何方法可以正常工作.

all*_*skd 22

这是我成功的尝试:

编辑路线文件并添加

POST    /upload                                 Application.upload
Run Code Online (Sandbox Code Playgroud)

我们的控制器是Application,我将使用它来保持简单.

编辑应用程序控制器类

public static void upload(String qqfile) {


if (request.isNew) {

    FileOutputStream moveTo = null;

    Logger.info("Name of the file %s", qqfile);
    // Another way I used to grab the name of the file
    String filename = request.headers.get("x-file-name").value();

    Logger.info("Absolute on where to send %s", Play.getFile("").getAbsolutePath() + File.separator + "uploads" + File.separator);
    try {

        InputStream data = request.body;


        moveTo = new FileOutputStream(new File(Play.getFile("").getAbsolutePath()) + File.separator + "uploads" + File.separator + filename);
        IOUtils.copy(data, moveTo);

    } catch (Exception ex) {

        // catch file exception
        // catch IO Exception later on
        renderJSON("{success: false}");
    }

}


renderJSON("{success: true}");
} 
Run Code Online (Sandbox Code Playgroud)

在app/views/Application文件夹/包中编辑您的Application.html

#{extends 'main.html' /}
#{set title:'Multiple Uploads' /}

<div id="file-uploader">
    <noscript>
        <p>Please enable JavaScript to use file uploader.</p>
        <!-- or put a simple form for upload here -->
    </noscript>

    <script>
        function createUploader(){
            var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader'),
                action: '/upload',
                debug: true
            });
        }

        // in your app create uploader as soon as the DOM is ready
        // don't wait for the window to load
        window.onload = createUploader;
    </script>    
</div>
Run Code Online (Sandbox Code Playgroud)

编辑主要布局:main.html,位于app/views文件夹/包中,并在jQuery之后添加此行

<script src="@{'/public/javascripts/client/fileuploader.js'}" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

最后的注意事项 请记住从AJAX上载Valums下载脚本,享受!

你也可以在这里获取资源.

我在不同的浏览器中测试过它至少对我有用.玩里亚德的积分!邮件列表谁暗示我request.body

PS:我之前使用的是我发布的评论

编辑 已经按照TJ Crowder的指示添加了代码答案,我同意:)