我正在尝试将juqery fileupload与ajax表单提交集成。 ajax表单发送文本并返回新创建的事件的ID。这是在上载时知道要链接的事件所必需的。 简单的上传演示使用以下代码
这是首先上传非文件字段的ajax
$.ajax({
type: 'post',
url: '/whats-on/upload-event/',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (return_data) {
console.log(return_data)
}
});
返回以下json
Object {status: true, id: 17162}
然而,fileupload在不声明data: data,
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" data-url="server/php/">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
//Returns ID as e['id'] and 200 status also with e['status']
}
});
});
</script>
</body>
</html>
答案 0 :(得分:1)
首先需要使用ajax帖子获取事件ID:
function uploadClick(){
var eventId = getEvent();
uploadFile(eventId)
}
function getEvent(){
// make an ajax and return your id
}
你得到它,然后创建一个带有指示eventId的查询字符串的URL。此URL是您要发布文件的位置:
function uploadFile(eventId){
// attatch the id to the URL with query string
url = url + '&eventId=' + eventId;
// submit here your file
}
这样你就可以在同一个ajax中调用文件本身和事件id。在服务器端操作中,您需要获取此查询字符串,然后选择已发布的文件。
答案 1 :(得分:0)
您可能必须处理fileupload插件的回调,例如:
$('#fileupload').fileupload({
url: <url>,
type: <HTTP_VERB>,
other configurations...
}).bind('fileuploadadd', function (e, data) {
//fires when you select a file to upload
}).bind('fileuploaddone', function (e, data) {
//fires when upload completed successfully. equivalent to done call back of jQuery ajax
}).bind('fileuploadfail', function (e, data) {
//fires when upload fails
});
如需完整参考,请查看以下link。