我想在跨域中将带有jquery-file-upload(blueimp)的文件上传到symfony2应用程序。
为此,客户方:
SLjQuery(function () {
'use strict';
SLjQuery('#media_answer_answer').fileupload({
url: "http://recrutonline.dev/app_dev.php/api/media/questionnaire-test-media/uploads",
dataType: 'text',
formData: SLjQuery('form#answer_process_form').serializeArray(),
forceIframeTransport: true,
redirect: 'http://mywebsite.dev/result.html?%s',
done: function (e, data) {
console.log('upload ok ', data)
},
progressall: function (e, data) {
console.log(data.loaded/data.total);
var progress = parseInt(data.loaded / data.total * 100, 10);
SLjQuery('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !SLjQuery.support.fileInput)
.parent().addClass(SLjQuery.support.fileInput ? undefined : 'disabled')
;
});
在我的控制器symfony中:
public function postMediaUploadAction(Request $request)
{
$requestData = $request->request->all();
$redirectResponse = $requestData['redirect']; // http://mywebsite.dev/result.html?%s
//...
//here process on data & get file uploaded
//...
//example of data I would send back to the client : http://mywebsite.dev/result.html?{'file':[{'name':'filetoupload.jpg'}]}
$response = str_replace("%s", "{'file':[{'name':'filetoupload.jpg'}]}", $redirectresponse); // is it the good method ?
return ??
}
现在收到客户方回复:
在'完成'的console.log中ajax函数的参数:
data.result -> undefined
data.textStatus -> "success"
我试图返回很多东西,但结果仍未定义。所以你知道我必须返回什么样的数据吗?
答案 0 :(得分:1)
您使用的是OneupUploaderBundle吗?
如果是这样,请不要将文件发布到您自己的控制器,而是将其发送到Oneup uploader endpoint。然后,您可以按implementing an event listener返回自定义数据。
例如:
namespace Foo\BarBundle\EventListener;
use Oneup\UploaderBundle\Event\PostPersistEvent;
class UploadListener
{
public function onUpload(PostPersistEvent $event)
{
if ($file = $event->getFile()) {
$response = $event->getResponse();
$response['file']['name'] = $file->getKey();
}
}
}
在services.yml(或xml文件)中注册此事件侦听器:
# Event listener to handle uploaded files
foo_bundle.upload_listener:
class: Foo\BarBundle\EventListener\UploadListener
tags:
- { name: kernel.event_listener, event: oneup_uploader.post_persist.default_uploader, method: onUpload }
当做想要自己处理上传时,我不建议您返回Symfony\Component\HttpFoundation\Response
甚至更好的Symfony\Component\HttpFoundation\JsonResponse
对象。请参阅documentation。