【问题标题】:How to get multiple images data in laravel controller(API) from ajax?如何从 ajax 获取 laravel 控制器(API)中的多个图像数据?
【发布时间】:2017-09-09 17:23:16
【问题描述】:

我的表格:

<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

如何从 ajax 检索数据(带图像)到控制器中的 store(API) 函数。

以便我可以处理和保存文件。

【问题讨论】:

  • 你试过images: $(this).find('#imageToUpload').val()而不是images: formData

标签: php jquery ajax laravel laravel-5.4


【解决方案1】:

您将图像存储为 base64 编码字符串并将其传递给服务器,然后服务器会将其转换回图像。

为此,请侦听图像输入的变化,并使用 FileReader 将图像转换为 base 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));

我怀疑这段代码是否完全准确,但应该是一个很好的起点。

【讨论】:

  • 有没有办法将多个图像数组附加到formdata并传递给控制器​​?
  • 当然,如您所见,$(this).prop("files") 返回一个数组,其中包含输入中的所有文件。所以你可以简单地迭代它并存储每个文件。
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
  • 2019-07-10
  • 1970-01-01
相关资源
最近更新 更多