2015-10-14 68 views
1

我有一个场景:我使用一些服务器位置上传一个文件:https://www.playframework.com/documentation/2.0/JavaFileUpload如何使用Play Framework和jQuery上传和显示文件?

//上传文件:

<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 

    }); 

但我的要求是:我只需要一种类型,既可以接受/上传服务器位置的文件,并返回/显示从我的查看页面上的服务器位置相同的文件路径?我正在努力。请帮帮我。

回答

2

这看起来像是一个类似的问题33163555。这个问题有下面的例子:

编辑:参考2320069对AJAX文件上传&方案支持:

从以下桌面FORMDATA支持浏览器开始的版本。 IE 10+,火狐4.0 +,Chrome的7 +,Safari 5以上,歌剧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");  
    } 
} 

而且你可以在阿贾克斯成功回调执行自定义的jQuery行动

+0

我得到内部服务器错误 – Dhana

+0

我们可以像上面这样实现它:http://stackoverflow.com/questions/33209460/how-to-redirect-to-same-overlay-on-return-statement-in-play-框架 – Dhana

+1

哦,抱歉哈哈。我没有意识到你发布了我引用的问题。编辑我的答案根据[2320069](http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload),[20452853](http://stackoverflow.com/questions/20452853/uploading-files-通过jQuery的对象形式数据是提供和无文件名称获得重新),[6974684](http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects -with-ajax-requests-in-jquery)其中说你需要在发送之前将你的文件存储到ajax formData对象中,或者采取另一种方法 – Chrizt0f

相关问题