Rah*_*ari 8 java file-upload playframework playframework-2.0 playframework-2.1
我正在使用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">
}
Run Code Online (Sandbox Code Playgroud)
我只想上传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());
}
Run Code Online (Sandbox Code Playgroud)
它是存储文件到临时目录,但我想存储到永久位置而不是临时目录作为文件而不是临时文件,如果我上传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>
Run Code Online (Sandbox Code Playgroud)
在我的控制器中我有:
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();
}
Run Code Online (Sandbox Code Playgroud)
就像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
)
}
Run Code Online (Sandbox Code Playgroud)
在此实现中,您可以将文件存储在指定的计算机上的任何位置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>
Run Code Online (Sandbox Code Playgroud)
希望所有这些都有帮助.
要将文件获取到临时位置以外的其他位置,您需要复制它,最好使用 apache commons 中的 FileUtils 之类的东西(http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io /FileUtils.html)
至于文件名,您可以从 MultipartFormData 获取它