我正在使用play framework 2.1.2
使用java ,我正在创建视图以上传多个文件,我的代码就在这里:
@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());
}
将文件存储到临时目录但是我希望存储到永久位置而不是临时目录作为文件而不是临时文件,就像我上传{{1}我想将此文件存储到存储空间,并使用a.docx
名称。
我不想将文件存储到数据库中。
和如何列出我按文件名上传的所有文件?
我发现了一些问题,但我没有得到答案,因为这个问题适用于旧版本。
给我一些解决这个问题的想法。
答案 0 :(得分:7)
以下是我实施的方法。如果我在某处犯了任何错误,我道歉。我“重构”它,使它看起来不像我的生产代码。
在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>
在我的控制器中我有:
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
中指定的位置。但是,如果要列出文件,则必须使用数据库。但您只需将文件路径存储为数据库中的String(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>
希望所有这一切都有帮助。
答案 1 :(得分:4)
要将文件放在除临时位置之外的其他位置,您需要复制它,最好使用来自apache commons的FileUtils(http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html)
至于文件名,您可以从MultipartFormData
获取它答案 2 :(得分:1)
一种方法是使用可以获取指定目录并将上传文件保存在那里的自定义主体解析器。但是你必须在项目中添加一些Scala代码。这是要点: