php - 如何在 laravel 4.2 中使用带有自定义预过滤器的 AJAX 上传 CSV 文件

标签 php jquery ajax laravel laravel-4

我正在使用 laravel 4.2,目前我不知道如何使用 AJAX 将 csv 文件保存到 public\csv\ 目录中。我仍在寻找一些答案。也许有人可以帮我解决这个问题。

这是我的代码:

在 Blade View 中:

 {{Form::open(['route' => 'file_upload', 'files' => true, 'id' => 'upload_form', 'method' => 'POST'])}}
    {{Form::file('csv_upload', ['id' => 'uploaded_file', 'accept' => 'text/csv'])}}
    {{Form::submit('submit', ['class' => 'btn btn-primary btn-xs', 'id' => 'upload'])}}
 {{Form::close()}}

Javascript Ajax:

var ajax_ready = 1
var token = {{Session::get('_token')}}

if($.type(originalOptions.data) === 'string') {
              options.data = originalOptions.data+"&_token="+token;
 }else if($.type(originalOptions.data) === 'object') {
         //Here I got a new error
 }else{
     options.data = $.param(($.extend(originalOptions.data, {'_token':mmad_token})));
 }

 options.url = originalOptions.url.slice(0,originalOptions.url.indexOf("?_token="));

   if (ajax_ready!=1){
              jqXHR.abort();
   }
  ajax_ready = 0;
});
$('form#upload_form').on('submit', function(e){
    e.preventDefault();
    var uploadFile =  $('#uploaded_file');

    var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
    var file = $('input[name="csv_upload"]').val();

    if($.inArray(ext, ["csv"]) === -1) {
             alert("Please upload a .csv file!");
             return false;
    }

     var csv = uploadFile[0].files;
     var form = new FormData(this);

     var csvFile = {lastModifed: csv[0].lastModified, fileName: csv[0].name, size: csv[0].size, fileType: csv[0].type};

      $.post('{{ URL::route("file_upload") }}?_token={{Session::token()}}',{
           data: form
      }).done(function(response){

      });

});

PHP:

public function upload_csv()
{
    $inputs = Input::all();

    $csvFile = $inputs['data']['fileName'];

    $path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
    $path2 = public_path('csv/');

    if(is_dir($path2))
    {
        @move_uploaded_file($csvFile, $path2.$csvFile); //This line can't move the uploaded files in my desired directory
    }

    return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);

}

以下代码在不使用 AJAX 时也能正常工作:

  if(Input::hasFile('csv_upload'))
    {
        $file = Input::file('csv_upload');

        $originalFilename = $file->getClientOriginalName();

        $rules = ['csv_upload' => 'required|file:csv'];

        $validate = Validator::make(['csv_upload' => $file], $rules);

        if($validate->fails())
        {
            return json_encode(['error' => 1, 'description' => 'File must be in .csv format']);
        }

        $path = public_path('/csv/');

        if(!file_exists($path))
        {
            mkdir($path);
        }
     }

csv的控制台日志

CSV DATA

最佳答案

您不能移动文件,因为当您使用 ajax 提交表单时 file is not being sent with ajax,For sending file you have to send file with FormData() javascript对象。

如果您通过放置 print_r($_FILES); checkin upload_csv Controller ,您将得到空数组。

所以使用FormData在客户端附加文件,然后尝试 agian。 你没有得到错误,因为你使用了 php 错误控制运算符 喜欢@move_uploaded_file($csvFile, $path2.$csvFile);

如果您需要工作示例,请告诉我,我会给您。

帮助代码: 1. 在 Blade View 中:

  <script type="text/javascript">
     $('form#upload_form').on('submit', function(e){
        e.preventDefault();
        var uploadFile =  $('#uploaded_file');

        var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
        var file = $('input[name="mmad_csv_upload"]').val();

        if($.inArray(ext, ["csv"]) === -1) {
                 alert("Please upload a .csv file!");
                 return false;
        }
        var csv = uploadFile[0].files;
        var formData = new FormData($(this)[0]);
        formData.append('uploaded_file', $("#uploaded_file")[0].files[0]);
        formData.append('lastModifed', csv[0].lastModified);
        formData.append('fileName', csv[0].name);
        console.log(formData);


        $.ajax({
        url: '{{ URL::route("file_upload") }}',
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) { //alert(returndata); return false;

        }
        });      

    });
 </script>

2. Controller

public function file_upload(Request $request)
{
    $inputs = Input::all();
    $csvFile = $inputs['fileName'];


    $path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
    $path2 = public_path('/csv/');
    if(is_dir($path2))
    {
        $success = $request->file('uploaded_file')->move($path2, $csvFile);
    }
    return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);

}

关于php - 如何在 laravel 4.2 中使用带有自定义预过滤器的 AJAX 上传 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33299545/

相关文章:

php - Sendgrid php发送给多个收件人

php - Tidy 破坏 anchor hrefs

javascript - 为什么 javascript 只换行一次(第一次)?

javascript - 通过滚动使 select2 元素保持固定大小?

javascript - 如何在ajax中使用相同的函数传递多个参数

php - AJAX PHP 上传问题

javascript - Ajax 调用未获得成功响应

php - 使用 cookie 的简单 PHP 登录

php - Symfony2 - 创建自己的供应商包 - 项目和 git 策略

php - 在 onclick div 上运行 php mysql_query