【问题标题】:uploading csv file using jquery ajax and codeigniter使用 jquery ajax 和 codeigniter 上传 csv 文件
【发布时间】:2017-03-18 12:16:55
【问题描述】:

这里我想使用 jquery ajax 函数上传和移动 csv 文件。

$("#file").change(function() { 
  alert($("#file").val());
  $.ajax({
    url: "<?php echo base_url(); ?>index.php/Task_controller/upload_tasksquestion",
    type: "post",
    dataType: 'json',
    processData: false,
    contentType: false,
    data: {file: $("#file").val()},
    success: function(text) {
        alert(text);
        if(text == "success") {
            alert("Your image was uploaded successfully");
        }
    },
    error: function() {
        alert("An error occured, please try again.");         
    }
  });   
});

我的html代码是:

< input type="file" class="form-control" id="file" name="file">

我正在测试控制器功能上传的文件名 比如 $this->input->post('file');

但它没有到达控制器,我想将该文件移动到一个文件夹中。 请帮助我在哪里做错了......

我的服务器端代码是:

$curdate=date('Y-m-d');
$path='./assets/fileuploads/';
$file=basename($_FILES['file']['name']);

list($txt, $ext) = explode(".", $file);
$actual_file_name = time().substr($txt, 5).".".$ext;
if(move_uploaded_file($_FILES['file']['tmp_name'],$path.$actual_file_name))

【问题讨论】:

    标签: jquery ajax codeigniter


    【解决方案1】:

    您需要使用FormData 通过 AJAX 发送文件。

    将文件存储在 FormData 对象中,并将该对象作为您的 data 传递。

    $("#file").change(function() {
        var fd = new FormData();
        fd.append('file', this.files[0]); // since this is your file input
    
        $.ajax({
            url: "<?php echo base_url(); ?>index.php/Task_controller/upload_tasksquestion",
            type: "post",
            dataType: 'json',
            processData: false, // important
            contentType: false, // important
            data: fd,
            success: function(text) {
                alert(text);
                if(text == "success") {
                    alert("Your image was uploaded successfully");
                }
            },
            error: function() {
                alert("An error occured, please try again.");         
            }
        });
    });
    

    阅读File Uploading Class(特别是从控制器部分)了解如何在服务器端处理文件。

    【讨论】:

    • 需要添加上传库吗?在服务器端?因为我正在测试,但它总是说发生错误。请帮助。
    • 根据说明需要加载Upload库。使用相关的服务器端代码编辑您的问题。错误可能意味着很多事情。打开您的浏览器开发者工具,找到显示所有 AJAX 请求的网络面板,然后找到给出的错误消息。
    • 这是我的服务器端代码:$config['upload_path'] = './assets/fileuploads/'; $config['allowed_types'] = '.csv/.CSV'; $this->load->library('upload', $config); echo $this->upload->do_upload('fd');这里只是想知道上传的文件名。
    猜你喜欢
    • 2015-05-11
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 2012-07-18
    • 2014-03-26
    相关资源
    最近更新 更多