繁体   English   中英

Play framework 2.2.x:Java中的图像上传

[英]Play framework 2.2.x: Image upload in Java

我是Play Framework的新手。 我正在使用Play framework v2.2.6作为我的REST-full后端应用程序。 我想为文件上传提供REST API,尤其是图像文件。 我正在用Java开发我的应用程序。

我搜索了很多,但我没有在Java中获得任何示例。 有人做过类似的事吗?

这就是我想做的事情:

  1. 提供上传图像文件的路径。
  2. 在控制器中,我想检查它是否是一个图像文件。 如果没有,则返回错误请求。
  3. 如果是图像文件,则将其保存在服务器上的文件系统中,并将该位置保存到该文件中。
  4. 提供检索已保存文件的路径。

几天前,我写了一个用于上传文件的最小示例应用程序,并将它们作为BLOB存储在您的数据库中: Github也许它对您有用...

html输入控件

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">

Javascript函数

function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
var src="";
if ('files' in x) {
    if (x.files.length == 0) {
        txt = "Select one or more files.";
    } else {
        for (var i = 0; i < x.files.length; i++) {
            txt += "<br><strong>" + (i+1) + ". file</strong><br>";
            var file = x.files[i];



            var data = new FormData();
            data.append('picture', file);
            jQuery.ajax({
                url: '/upload',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data){
                    alert(data);
                }
            });


            if ('name' in file) {
                txt += "name: " + file.name + "<br>";
            }
            if ('size' in file) {
                txt += "size: " + file.size + " bytes <br>";
            }
        }
    }
} 
else {
    if (x.value == "") {
        txt += "Select one or more files.";
    } else {
        txt += "The files property is not supported by your browser!";
        txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
    }
}

的console.log(TXT); }

路线

POST    /upload                         controllers.Application.upload

控制器

public static Result upload() {
      MultipartFormData body = request().body().asMultipartFormData();
      FilePart picture = body.getFile("picture");
      if (picture != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType(); 
        File file = picture.getFile();
        return ok("File uploaded");
      } else {
        flash("error", "Missing file");
        return redirect(routes.Application.index());    
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM