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

时间:2022-08-25 16:25:39

I'm using laravel 4.2 and currently I don't how to save a csv file into public\csv\ directory using AJAX. I'm still finding some answers. Maybe someone can help me with this.

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

Here's my code:

这是我的代码:

In 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:

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:

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']);

}

This code below does work when not using AJAX:

不使用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);
        }
     }

Console.log of csv

console.log的csv

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

4 个解决方案

#1


5  

You can not move file because when you submit form with ajax file is not being sent with ajax,For sending file you have to send file with FormData() javascript Object.

您无法移动文件,因为当您使用ajax文件提交表单时没有使用ajax发送,对于发送文件,您必须使用FormData()javascript对象发送文件。

If you check in upload_csv controller by putting print_r($_FILES); you will get empty array.

如果你通过put_j($ _ FILES)来检查upload_csv控制器;你会得到空数组。

So use FormData on client side for appending file, then try agian. You aren't getting error beacuse you have used php Error Control Operators likes@move_uploaded_file($csvFile, $path2.$csvFile);.

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

if you need working example then tell me i will give it to you.

如果你需要工作的例子那么告诉我,我会把它给你。

Code For Your Help: 1. In blade view:

代码为您的帮助:1。在刀片视图中:

  <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

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']);

}

#2


0  

To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:

要将上载的文件移动到新位置,您应该使用move方法。此方法将文件从其临时上载位置(由PHP配置确定)移动到您选择的更永久的目标位置:

Input::file('fileName')->move($destinationPath, $fileName);

If you need additional validations, you can check it at http://laravel.com/docs/5.1/requests#files

如果您需要其他验证,可以访问http://laravel.com/docs/5.1/requests#files进行检查

#3


0  

Default AJAX POST does not support file uploads. Use jQuery Form to upload files successfully. Full documentation of file upload at http://malsup.com/jquery/form/#file-upload

默认的AJAX POST不支持文件上传。使用jQuery Form成功上传文件。有关文件上传的完整文档,请访问http://malsup.com/jquery/form/#file-upload

Below my example of a recentlty build script... My Controller uploads the files to S3, but is easy to be implemented with local storage.

在我最近构建脚本的示例下面......我的控制器将文件上传到S3,但很容易用本地存储实现。

var progress = function(event, position, total, percent) {
    $(".progress-bar").width(percent + '%');
    $(".progress-bar").html(percent + '%');
    if(percent > 50) {
        $(".progress-bar").css('color','#fff');
    }
    if(percent == 100) {
        setTimeout(function(){
            $(".progress").html('<span class="processing-msg">Processing... Please be patient!</span>');
            $(".processing-msg").fadeIn('slow');
        }, 1000);
    }
}

var success = function(data) {
    var obj = $.parseJSON(data);
    $("#"+obj.hidden, parent.document).val(obj.filename);
    var src = 'https://s3.amazonaws.com/spincms'+obj.path+'thumb_'+obj.filename;
    $("#uploaded-"+obj.hidden, parent.document).html('<img class="img-circle uploaded-img" src="' + src + '">');
    $(".progress").html('<span class="processing-msg-next">File has been uploaded and processed. Do not forget to submit the form!</span>');
}

var options = {
    target: '#output',
    uploadProgress: progress,
    success: success,
    resetForm: true
};

$(document).on('click', "#upload-now", function(e) {
    $(".progress").html('<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>');
    if($("#upload-form input[type=file]")[0].files.length == 0) {
        $(".progress").html('<span class="processing-msg-next">No file selected!</span>');
        return false;
    } else {
        var name = $("#upload-form input[name='name']").val();
        var token = $("#upload-form input[name='_token']").val();
        var file_name = $("#upload-form input[type=file]")[0].files[0].name;
        $("#upload-form").ajaxSubmit(options);
        }
    }
});

#4


0  

Since you are using jQuery you can use the form plugin as it will make things much more easier for you to work with for example , this is the jquery part that you will use :

由于您使用的是jQuery,因此可以使用表单插件,因为它可以使您更容易使用,例如,这是您将使用的jquery部分:

$(document).ready(function() { 
    // bind 'myForm' and provide a simple callback function 
    $('#upload_form').ajaxForm(function() { 
        alert("Your file has been uploaded, thanks"); 
    }); 
}); 

and in your controller you can code it like :

在您的控制器中,您可以像下面这样编码:

pubilc function postUpload()
{
    $success = false;
    if(Request::ajax())
    {
        if(Input::hasFile('csv_upload'))
        {
            $file = Input::file('csv_upload');
            if(!File::isDirectory(storage_path('csv'))) {
                File::createDirectory(storage_path('csv'));
            }

            $file->move(storage_path('csv'), $file->getClientOriginalName());
            // now your file is on app/storage/csv folder
            $filePath = storage_path('csv/'.$file->getClientOriginalName());
            $success = true;
        }   
    }


    return Response::json(['success'=>$success]);
}

#1


5  

You can not move file because when you submit form with ajax file is not being sent with ajax,For sending file you have to send file with FormData() javascript Object.

您无法移动文件,因为当您使用ajax文件提交表单时没有使用ajax发送,对于发送文件,您必须使用FormData()javascript对象发送文件。

If you check in upload_csv controller by putting print_r($_FILES); you will get empty array.

如果你通过put_j($ _ FILES)来检查upload_csv控制器;你会得到空数组。

So use FormData on client side for appending file, then try agian. You aren't getting error beacuse you have used php Error Control Operators likes@move_uploaded_file($csvFile, $path2.$csvFile);.

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

if you need working example then tell me i will give it to you.

如果你需要工作的例子那么告诉我,我会把它给你。

Code For Your Help: 1. In blade view:

代码为您的帮助:1。在刀片视图中:

  <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

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']);

}

#2


0  

To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:

要将上载的文件移动到新位置,您应该使用move方法。此方法将文件从其临时上载位置(由PHP配置确定)移动到您选择的更永久的目标位置:

Input::file('fileName')->move($destinationPath, $fileName);

If you need additional validations, you can check it at http://laravel.com/docs/5.1/requests#files

如果您需要其他验证,可以访问http://laravel.com/docs/5.1/requests#files进行检查

#3


0  

Default AJAX POST does not support file uploads. Use jQuery Form to upload files successfully. Full documentation of file upload at http://malsup.com/jquery/form/#file-upload

默认的AJAX POST不支持文件上传。使用jQuery Form成功上传文件。有关文件上传的完整文档,请访问http://malsup.com/jquery/form/#file-upload

Below my example of a recentlty build script... My Controller uploads the files to S3, but is easy to be implemented with local storage.

在我最近构建脚本的示例下面......我的控制器将文件上传到S3,但很容易用本地存储实现。

var progress = function(event, position, total, percent) {
    $(".progress-bar").width(percent + '%');
    $(".progress-bar").html(percent + '%');
    if(percent > 50) {
        $(".progress-bar").css('color','#fff');
    }
    if(percent == 100) {
        setTimeout(function(){
            $(".progress").html('<span class="processing-msg">Processing... Please be patient!</span>');
            $(".processing-msg").fadeIn('slow');
        }, 1000);
    }
}

var success = function(data) {
    var obj = $.parseJSON(data);
    $("#"+obj.hidden, parent.document).val(obj.filename);
    var src = 'https://s3.amazonaws.com/spincms'+obj.path+'thumb_'+obj.filename;
    $("#uploaded-"+obj.hidden, parent.document).html('<img class="img-circle uploaded-img" src="' + src + '">');
    $(".progress").html('<span class="processing-msg-next">File has been uploaded and processed. Do not forget to submit the form!</span>');
}

var options = {
    target: '#output',
    uploadProgress: progress,
    success: success,
    resetForm: true
};

$(document).on('click', "#upload-now", function(e) {
    $(".progress").html('<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>');
    if($("#upload-form input[type=file]")[0].files.length == 0) {
        $(".progress").html('<span class="processing-msg-next">No file selected!</span>');
        return false;
    } else {
        var name = $("#upload-form input[name='name']").val();
        var token = $("#upload-form input[name='_token']").val();
        var file_name = $("#upload-form input[type=file]")[0].files[0].name;
        $("#upload-form").ajaxSubmit(options);
        }
    }
});

#4


0  

Since you are using jQuery you can use the form plugin as it will make things much more easier for you to work with for example , this is the jquery part that you will use :

由于您使用的是jQuery,因此可以使用表单插件,因为它可以使您更容易使用,例如,这是您将使用的jquery部分:

$(document).ready(function() { 
    // bind 'myForm' and provide a simple callback function 
    $('#upload_form').ajaxForm(function() { 
        alert("Your file has been uploaded, thanks"); 
    }); 
}); 

and in your controller you can code it like :

在您的控制器中,您可以像下面这样编码:

pubilc function postUpload()
{
    $success = false;
    if(Request::ajax())
    {
        if(Input::hasFile('csv_upload'))
        {
            $file = Input::file('csv_upload');
            if(!File::isDirectory(storage_path('csv'))) {
                File::createDirectory(storage_path('csv'));
            }

            $file->move(storage_path('csv'), $file->getClientOriginalName());
            // now your file is on app/storage/csv folder
            $filePath = storage_path('csv/'.$file->getClientOriginalName());
            $success = true;
        }   
    }


    return Response::json(['success'=>$success]);
}