1.编写文件上传需要的模板 fileupload.scala.html
@(title: String)
<!DOCTYPE html>
<html><head><title>@title</title></head><body><h1>普通的文件上传</h1><form action="/upload" id="formData" method="post" enctype="multipart/form-data"><input type="file" name="file"/><input type="submit" value="上传文件"/></form><h1>使用Ajax的文件上传</h1><form action="" id="formData" enctype="multipart/form-data"><input type="file" name="file" id="file"><input type="button" value="上传文件" id="upload"></form></body>
</html>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript">$(document).on('click', "#upload", function () {var formData = new FormData($("#formData")[0]);console.log($('#file').get(0).files[0]);formData.append("file", $('#file').get(0).files[0])$.ajax({url: '/ajaxUpload',type: 'post',async: true,cache: false,contentType: false,processData: false,dataType: 'json',data: formData,success: function (data) {console.info(data)},error: function (data) {console.log(data)}});});
</script>
2.编写文件上传的action FileController
package controllersimport java.io._import javax.inject.{Inject, Singleton}
import play.api.libs.Files
import play.api.libs.json.Json
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AbstractController, ControllerComponents}import scala.util.Random/*** @author 梦境迷离* @version 1.0, 2019-03-23*/
@Singleton
class FileController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {/*** 显示上传页面** @return*/def toUpload = Action {Ok(views.html.fileupload("文件上传"))}/*** 使用ajax的文件上传** @return*/def ajaxUpload() = Action(parse.multipartFormData) {implicit request => {request.body.file("file").map(file => uploadFile(file)).getOrElse(Ok(Json.obj("status" -> "FAIL")))}}/*** 文件上传** @return*/def upload() = Action(parse.multipartFormData) {implicit request => {request.body.file("file").map(file => uploadFile(file)).getOrElse(Ok(Json.obj("status" -> "FAIL")))}}private val uploadFile = (file: FilePart[Files.TemporaryFile]) => {val fileName = file.filenameprintln(s"文件名:$fileName")var nameSuffix = ""//检测文件是否存在后缀名if (fileName.lastIndexOf(".") > -1) {nameSuffix = fileName.substring(fileName.lastIndexOf("."))println(s"后缀名:$nameSuffix")}//给文件取新的随机名val newName = new Random().nextInt(1000000000)//目标目录路径val toFile: File = new File("D:/git_project/scala_play_learn/temp/")if (!toFile.exists()) {//不存在就创建新的文件夹toFile.mkdir()}//准备存放的文件val f = new File(s"D:/git_project/scala_play_learn/temp/$newName$nameSuffix")//将文件移动到新的文件file.ref.moveFileTo(f, true)Ok(Json.obj("status" -> "OK"))}
}
3.添加action路由配置
#不拦截url
+ nocsrf
POST /upload controllers.FileController.upload
POST /ajaxUpload controllers.FileController.ajaxUpload
GET /toUpload controllers.FileController.toUpload
4.配置Csrf 拦截 application.conf中增加
play.filters {csrf.header.bypassHeaders {##不拦截ajaxX-Requested-With = "*"Csrf-Token = "nocheck"}
}
非ajax的post必须加+ nocsrf 或者为ajax请求加X-Requested-With = "*"
5.启动App 访问 localhost:9000/toUpload
PS:ajax上传的结果没有使用弹窗,需要通过浏览器debug模式的console来查看。