我正在使用 play framework 2.1.2
使用 java 我正在创建 View 来上传多个文件,我的代码在这里:
@form(action = routes.upload.up, 'enctype -> "multipart/form-data") {
<input type="file" name="picture" accept="application/pdf" multiple="multiple"><br/>
<input type="submit" value="upload">
}
我只想上传doc 和pdf 文件。
如何限制表单只上传doc和pdf文件?
我可以用 java 做到这一点,但我正在寻找 html 代码。
在此之后我想将多个文件存储到我的计算机中的永久存储中。
并打印我上传的文件名。
我的代码:
public static Result up(){
MultipartFormData md=request().body().asMultipartFormData();
List<FilePart>file;
file=md.getFiles();
for(FilePart p: file){
Logger.info(p.getFilename());
}
return ok(file.get(0).getFilename());
}
它是将文件存储到临时目录但我想存储到永久位置而不是临时目录作为文件而不是临时文件就像我上传a .docx
我想用 a.docx
名称将此文件存储。
我不想将文件存储到数据库中。
和如何按文件名列出我上传的所有文件?
我发现了一些问题,但我没有得到答案,因为该问题是针对旧版本的。
给我一些解决这个问题的想法。
最佳答案
下面是我如何实现我的。如果我在某个地方犯了任何错误,我深表歉意。我“重构”了它,使其看起来与我的生产代码完全不同。
在 HTML 中我有:
<form name="fileUploadForm" method="POST" enctype="multipart/form-data" action="@routes.Application.upload()">
File 1: <br /> <input type="file" name="filePart1" id="filePart1"><br />
File 2: <br /> <input type="file" name="filePart2" id="filePart1"><br />
</form>
在我的 Controller 中我有:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
FilePart filePart2 = body.getFile("filePart2");
File newFile1 = new File("path in computer");
File newFile2 = new File("path in computer");
File file1 = filePart1.getFile();
File file2 = filePart2.getFile();
InputStream isFile1 = new FileInputStream(file1);
InputStream isFile2 = new FileInputStream(file2);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
byte[] byteFile2 = IOUtils.toByteArray(isFile2);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
FileUtils.writeByteArrayToFile(newFile2, byteFile2);
isFile1.close();
isFile2.close();
}
就像 Kris 说的,你必须得到 Apache 的 CommonIO
你可以很容易地做到这一点,将它添加到/PlayProject/project 中的 Build.scala 中:
import sbt._
import Keys._
import play.Project._
import com.typesafe.config._
object ApplicationBuild extends Build {
val appDependencies = Seq(
"commons-io" % "commons-io" % "2.4" //add this here
)
}
在此实现中,您可以将文件存储在计算机上您在 File newFile1
中指定的任何位置。但是如果你想列出你的文件,你将不得不使用数据库。但是您只需将文件路径作为字符串 (varchar) 存储在数据库中。我将把这部分留给您自己解决,因为我不知道您想如何处理文件检索。
您可以使用 Javascript 限制用户只能上传特定类型的文件。让 Javascript 通过检查文件名来进行表单验证:这是一个示例:
<script>
var file1 = document.getElementById("filePart1").value;
if (file1.indexOf(".pdf") == -1) {
alert("Not a PDF file!");
else {
document.fileUploadForm.submit();
}
</script>
希望所有这些对您有所帮助。
关于java - 如何使用 Play Framework 上传多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18441313/