Play Framework/Scala中的多个上载控制器

Play Framework/Scala中的多个上载控制器,scala,playframework-2.0,multipartform-data,Scala,Playframework 2.0,Multipartform Data,我试图从“多部分/表单数据”表单上载多个文件,并将它们全部存储在具有批ID(这只是一个时间戳)的文件夹中 问题是我目前只能保存一个文件 看法 这与reqest.body.file只获取一个文件有关,还是应该遍历数组或其他内容?我对scala还不太熟悉,因此非常感谢您的帮助。我花了一段时间才弄明白,可能还有更优雅的解决方案,但鉴于您已经等待了6个月,我将向您展示我丑陋的解决方案: 在前端,我使用XHR将文件发送到服务器,并将文件分别附加到表单中: 上传文件作为一个列表被证明是更具挑战性的,我也只能

我试图从“多部分/表单数据”表单上载多个文件,并将它们全部存储在具有批ID(这只是一个时间戳)的文件夹中

问题是我目前只能保存一个文件

看法


这与reqest.body.file只获取一个文件有关,还是应该遍历数组或其他内容?我对scala还不太熟悉,因此非常感谢您的帮助。

我花了一段时间才弄明白,可能还有更优雅的解决方案,但鉴于您已经等待了6个月,我将向您展示我丑陋的解决方案:

在前端,我使用XHR将文件发送到服务器,并将文件分别附加到表单中:

上传文件作为一个列表被证明是更具挑战性的,我也只能得到该列表中第一个文件的引用

@helper.form(action = routes.Application.upload, 'enctype -> "multipart/form-data", 'multiple -> "") {

<input type="file" name="fsa" multiple="">

<p>
    <input type="submit">
</p>

}
def upload = Action(parse.multipartFormData) { request =>
            request.body.file("fsa").map { fsa =>
            import java.io.File
                val filename = fsa.filename 
                val contentType = fsa.contentType
                val timestamp: Long = System.currentTimeMillis / 1000
                fsa.ref.moveTo(new File("/tmp/"+timestamp+"/"+filename))
                Ok("File uploaded")
            }.getOrElse {
                Redirect(routes.Application.index).flashing(
                    "error" -> "Missing file"
                )
            }
    }
var uploadFiles = document.getElementById("file-input").files;

var formData = new FormData();
for (var i = 0; i < uploadFiles.length; i++) {
    console.log("appending " + uploadFiles[i].name);
    formData.append(uploadFiles[i].name, uploadFiles[i]);
}

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("load", function(e) {
    console.log("upload successful");
}, false);
xhr.upload.addEventListener("progress", function updateProgress(event) {
    if (event.lengthComputable) {
        var percentComplete = (event.loaded / event.total)*100;
        console.log("Completed: " + percentComplete);
    }
}, false);
xhr.open('POST', UPLOAD_URL, true);

xhr.send(formData);
object Api extends Controller {

    def upload = Action(parse.multipartFormData) { request =>
        println("Api.upload()")
        LibraryService.uploadFiles(request.body.files)
        Ok("Upload complete")
    }
}


object LibraryService {

    val libraryRoot: String = Play.configuration.getString("library.root").get;

    def uploadFiles(files: Seq[FilePart[TemporaryFile]]) = {
        files.foreach { filePart =>
            val newFile = new File(libraryRoot + filePart.filename)
            if (newFile.exists) {
                println("The file " + newFile.getAbsolutePath + " already exists. Upload cancelled.")
            } else {
                filePart.ref.moveTo(newFile)
            }
        }
    }
}