嘿,大家好,我在symfony3中使用ajax上傳文件時遇到問題我檢測到沒有提交或用ajax,jquery點擊文件的事件,但是我沒有任何東西在方法控制器中獲取請求總是空如何在symfony3中使用ajax jquery上傳文件
第一的console.log(file_data)返回
File {name: "pawandeep.jpg", lastModified: 1489747066000, lastModifiedDate: Fri Mar 17 2017 11:37:46 GMT+0100 (Paris, Madrid), webkitRelativePath: "", size: 30970…}
最後的console.log(數據)返回NULL!
<form method="post" action="#" id = "myForm" enctype="multipart/form-data" >
<div id="mybutton">
<input type="file" id="myfile" name="upload"/>
Click Me!
</div>
</form>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
</div>
</div>
<script>
$(document).ready(function() {
$('.progress').hide();
$('#myfile').change(function(evt) {
/*srcPhoto = $(this).val();*/
$('.progress').show();
var file_data = $("#myfile").prop("files")[0];
console.log(file_data);
var form_data = new FormData(file_data); // Creating object of FormData class
/*form_data.append("file", file_data)*/
/*form_data.append("id", "{{ doctor.id }}")*/
if(file_data != ""){
$.ajax({
url: "{{ path('bonjou', {'id':doctor.id}) }}", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: form_data, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
mimeType: "multipart/form-data",
dataType:"json",
success: function (data) // A function to be called if request succeeds
{
$(".progress").hide();
console.log(data);
$(".photoDoctor").attr("src", data.name);
}
});
};
});
});
</script>
文件生根
bonjou:
path: /akrem/{id}
defaults: { _controller: DoctorsAdminBundle:Doctor:akrem }
方法控制
public function akremAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$doctor = $em->getRepository('DoctorsAdminBundle:Doctor')->find($id);
$file = $request->files->get('upload');
$countryArray = array(
'file'=>$file
);
return new \Symfony\Component\HttpFoundation\JsonResponse($countryArray);
}
無第一個console.log(file_data)返回undefined !! –
你正在嘗試傳遞文件individualy nstead嘗試通過整個表單,它會得到你的結果 –
虐待示例 –