如何使用Play Framework和jQuery上传和显示文件?

时间:2015-10-14 05:49:27

标签: javascript jquery html playframework

我有一个场景:我使用以下内容在某个服务器位置上传一个文件:https://www.playframework.com/documentation/2.0/JavaFileUpload

//上传文件:

<input type="file" name="fileUpload">
<input type="submit" value="Upload">

从下面的代码中,我上传了上面上传的文件并在我的视图页面上显示/显示它(点击提交按钮后):

<input type="file" id="inputfile">
<input type="button" value="Submit" id="submitfile">

jQuery的:

$("#submitfile").click(function(){
    var path1 =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');//uploaded file names 
    //adding the Play framework server path for Application to get the image(s) file(s) path
    var filespath = '/files/images/'+path1;//giving my uploaded files path here

    });

但我的要求是:我只需要一种同时执行这两种操作的类型:在服务器位置接受/上传文件并从我的视图页面上的服务器位置返回/显示相同的文件路径?我正在努力。请帮帮我。

1 个答案:

答案 0 :(得分:2)

这与33163555类似。这个问题有以下例子:

修改:参考2320069以获取有关ajax文件上传和支持的支持替代方案:

  

FormData支持从以下桌面浏览器版本开始。 IE   10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12 +

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<form enctype="multipart/form-data">
  <input type="file" id="file" name="file" />
  <input type="submit" id="submit" name="" value="Upload" />
</form>

<script>
$('#submit').click(function (event) {
   event.preventDefault();
   var file = $('#file').get(0).files[0];
   var formData = new FormData();
   formData.append('file', file);
   $.ajax({
       url: 'upload',
       data: formData,
       type: 'POST',
       contentType: false,
       processData: false,
       beforeSend: function (data) {
         alert('Are you sure you want to upload document?');
       },
       success: function (data) {
         //call your jQuery action here
         alert('Upload completed: ' + data);
       },
       error: function (jqXHR, textStatus, errorThrown) {
         alert(textStatus + ': ' + errorThrown);
       }
    });
    return false;
});
</script>

在您的路线中,您有:

POST /upload controllers.Application.upload()

您的控制器方法返回文件路径的位置:

public static Result upload() {
  MultipartFormData body = request().body().asMultipartFormData();
  FilePart fileP = body.getFile("file");
  if (fileP != null) {
    File file = fileP.getFile();
    //If we want to move from temp
    //FileUtils.moveFile(file.getCanonicalPath(), "FileB"); 
    return ok(file.getCanonicalPath());
  } else {
    return badRequest("Upload Error");    
  }
}

您可以在ajax成功回调中执行自定义jQuery操作