PlayFramework:Ajax + Drag n' Drop + File Upload +控制器中的文件对象?
有谁知道通过 Ajax 上传文件并使用从桌面拖放支持 PlayFramework 将文件上传转换为 File 对象的能力的方法?
Does anyone know of a way to upload a file via Ajax and using drag n' drop from the desktop that supports PlayFramework's ability to convert file uploads to a File object?
我尝试了几种不同的方法,但都没有正常工作.
I've tried several different methods, and nothing works correctly.
推荐答案
这是我的成功尝试:
编辑路由文件并添加
POST /upload Application.upload
我们的控制器是Application
,我将使用它来保持简单.
Our controller is Application
, I'll be using it to keep it simple.
编辑您的应用程序控制器类
public static void upload(String qqfile) {
if (request.isNew) {
FileOutputStream moveTo = null;
Logger.info("Name of the file %s", qqfile);
// Another way I used to grab the name of the file
String filename = request.headers.get("x-file-name").value();
Logger.info("Absolute on where to send %s", Play.getFile("").getAbsolutePath() + File.separator + "uploads" + File.separator);
try {
InputStream data = request.body;
moveTo = new FileOutputStream(new File(Play.getFile("").getAbsolutePath()) + File.separator + "uploads" + File.separator + filename);
IOUtils.copy(data, moveTo);
} catch (Exception ex) {
// catch file exception
// catch IO Exception later on
renderJSON("{success: false}");
}
}
renderJSON("{success: true}");
}
在 app/views/Application 文件夹/包中编辑您的 Application.html
#{extends 'main.html' /}
#{set title:'Multiple Uploads' /}
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
<script>
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/upload',
debug: true
});
}
// in your app create uploader as soon as the DOM is ready
// don't wait for the window to load
window.onload = createUploader;
</script>
</div>
编辑您的主布局:main.html,位于 app/views 文件夹/包中,并在 jQuery 之后添加这一行
<script src="@{'/public/javascripts/client/fileuploader.js'}" type="text/javascript"></script>
结语记得从 AJAX Upload Valums 下载脚本,尽情享受吧!
Final notes Remember to download the script from AJAX Upload Valums, enjoy!
您也可以在此处获取源代码.
我在不同的浏览器中对其进行了测试,它至少对我有用.归功于 Riyad in Play!向我暗示 request.body
I tested it in different browsers it works for me at least. Credits to Riyad in Play! mailing list who hinted me about the request.body
P.S:我使用的是我之前发布的评论
P.S: I'm using the one I posted as a comment before
编辑已按照 T.J. 的指示添加了带有代码的答案.克劳德,我同意:)
Edit The answer with code has been added as directed by T.J. Crowder, I agree :)
相关文章