[英]Multiple Upload Controller in Play Framework / Scala
我正在嘗試從“multipart / form-data”表單上傳多個文件,並將它們全部存儲在具有批次ID的文件夾中(這只是一個時間戳)
問題是我目前只能保存一個文件。
視圖
@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"
)
}
}
這與reqest.body.file只有一個文件有關,還是應該迭代一個數組? 不太熟悉scala,所以任何幫助升值。
我花了一段時間才弄清楚,可能會有更優雅的解決方案,但看到你已經等了6個月,我會告訴你我丑陋的解決方案:
在前端,我使用XHR將文件發送到服務器,將文件單獨附加到表單:
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)
}
}
}
}
上傳文件作為列表證明更具挑戰性,我也只能獲得對該列表中第一個文件的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.