2017-04-13 19 views
0

我的形式:如何從ajax獲取laravel控制器(API)中的多個圖像數據?

<form enctype="multipart/form-data" method="post" id="createProduct"> 
{{ csrf_field() }} 
<input required name="name" type="text"> 
<textarea name="description"></textarea> 
<input id="imageToUpload" type="file"name="images[]" multiple/> 
<input type="submit" value="submit"/> 
</form> 

我的腳本:

$(document).ready(function(){ 
$.ajaxSetup({ 
    headers: { 
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
    } 
}); 
$('#createProduct').on('submit', function(e){ 
e.preventDefault(e); 
var redirect_url = "{{ route('products.list') }}"; 
var url = "{{ route('products.store') }}"; 
var method = $(this).attr('method'); 
var formData = new FormData; 
for(var i = 0; i < images.length; i++){ 
    formData.append(images[i].name, images[i]) 
} 
var myData = { 
    name: $(this).find("[name='name']").val(), 
    description: $(this).find("[name='description']").val(), 
    images: formData 
} 
$.ajax({ 
    type: method, 
    url: url, 
    dataType: 'JSON', 
    data: myData, 
    cache: false, 
    contentType: false, 
    processData: false, 
    success: function(data){ 
    console.log(data); 
    window.location.href = redirect_url; 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     console.log(JSON.stringify(jqXHR)); 
     console.log("AJAX error: " + textStatus + ' : ' + errorThrown); 
    } 
}); 
}); 

我的控制器:

public function store(Request $request){ 
$input = Input::all(); 
return Response::json([ 
    'message' => 'Product Created Succesfully', 
    'data' => $input 
], 200); 

如何從表單發送數據(與圖像)阿賈克斯

如何從ajax中檢索數據(包含圖像)以存儲(API)功能到控制器中。

這樣我就可以處理和保存文件。

+0

有沒有嘗試'圖像:$(this).find('#imageToUpload')。val()'而不是'images:formData' –

回答

0

您將圖像存儲爲base64編碼的字符串並將其傳遞給服務器,然後將其轉換回圖像。

這樣做監聽上的圖像輸入的變化,並且將圖像轉換爲具有的FileReader基座64:

$("#imageToUpload").change(function() { 
var file = $(this).prop("files")[0]; 
    if (file != undefined) { 
     var reader = new FileReader(); 

     reader.addEventListener("loadstart", function() { 
      // You can do something to tell the user the conversion started 
     }); 

     // Store the file as a base64 string 
     reader.addEventListener("load", function() { 
      myData.image = reader.result; 
      // Get the name of the file, removing the path 
      myData.imageName = $(this).val().replace(/^.*[\\\/]/, '') 
     }); 

     reader.readAsDataURL(file); 
    } 
}); 

然後在控制器讀它,並將它與file_put_contents()存儲:

// Get rid of the base64 header to parse the image 
list($type, $input->image) = explode(';', $input->image); 
list(, $input->image)  = explode(',', $input->image); 
// Store the image 
file_put_contents("/your/path" . $input->imageName, base64_decode($input->image)); 

我懷疑這段代碼是完全準確的,但應該是一個很好的起點。

+0

有沒有辦法將多個圖像數組添加到formdata並傳遞給控制器? –

+0

當然,你可以看到'$(this).prop(「files」)'返回一個包含輸入中所有文件的數組。所以你可以簡單地迭代它並存儲每個文件。 – lluchmk

相關問題