【问题标题】:How can i upload image with ajax in codeigniter?如何在codeigniter中使用ajax上传图片?
【发布时间】:2015-01-31 22:12:01
【问题描述】:

我正在尝试使用 jQuery 和 ajax 函数上传图像,如何获取图像文件的所有详细信息,例如在 php 中我们使用 $_FILE()

这是我的代码

JS

$("#uploadimg" ).click(function() {
     $( "#file" ).click();
});

$( "#file" ).change(function(e) {
    var file=$('#file').val();
    alert(file);
    die();
    e.preventDefault();
    $.ajax({
        url:'http://localhost/JSG/blog/uploadimg',
        secureuri:false,
        type: "POST",
        fileElementId:'image',
        dataType: 'text',
        data:{ file: file },
        cache: true,
        success: function (data){
            alert(data);
            console.log(data);
        },
    });
});

控制器

public function uploadimg()
{
    $var = $_POST['file'];
    print_r($var);
    if($this->input->post('file')) {
        $config['upload_path'] = 'upload'; 
        $config['file_name'] = $var;
        $config['overwrite'] = 'TRUE';
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = '1024';
        $config["max_width"] = '400';
        $config["max_height"] = '400';
        $this->load->library('upload', $config);

        if(!$this->upload->do_upload()) {
            $this->data['error'] = $this->upload->display_errors();
            print_r( $this->data['error']);
        } else {
            print_r("success");
        }
    }
}

查看

<form role="form">
    <div class="form-group">
        <label for="recipient-name" class="control-label">Blog Title:</label>
        <input type="text" class="form-control" id="recipient-name">
    </div>
    <div class="form-group">
        <label for="message-text" class="control-label">Message:</label>
        <textarea class="form-control" id="message-text"></textarea>
    </div>
    <div class="form-group">
        <label for="message-text" class="control-label">Upload image:</label>
        <img src="<?php echo base_url();?>assest/img/blank.png" alt="Blank image" id="uploadimg" class="img-thumbnail">
        <input style="display:none" id="file" value=" " type="file" class="file" data-show-preview="false">
    </div>
</form>

回应

C:\fakepath\Koala.jpg 您没有选择要上传的文件。

请帮忙

【问题讨论】:

    标签: php jquery ajax codeigniter


    【解决方案1】:

    您可以在 html5 中使用 FormData api。

    您的表格必须是:

    <form enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname"  method="post" action="">
    

    然后是jquery:

    function uploadImage() {
    
        if (typeof FormData !== 'undefined') {
    
            // send the formData
            var formData = new FormData( $("#formID")[0] );
    
            $.ajax({
                url : baseUrl + 'uploadImage',  // Controller URL
                type : 'POST',
                data : formData,
                async : false,
                cache : false,
                contentType : false,
                processData : false,
                success : function(data) {
                    successFunction(data);
                }
            });
    
        } else {
           message("Your Browser Don't support FormData API! Use IE 10 or Above!");
        }   
    }
    

    然后在控制器中你会得到$_FILES数组中的文件。

    【讨论】:

    • 当我在控制器中使用 $_FILES 时,他的 throw [Object FileData] 出现了一些问题..请帮助
    • 我没有得到实际值如何使用完整的文件路径。
    • 您必须检查 - $_FILES ['name'] 其中 'name' 是输入类型 = 文件的名称。您还必须为所有输入提供名称属性。使用 var_dump() 查看信息。
    • @John,我只是想知道你为什么在 $("#formID")[0]) 中使用 [0]?
    【解决方案2】:

    在您显示表单的视图中:

    添加属性:enctype=multipart/form-data

    或者,

    如果您使用表单助手创建表单:

    <?php echo form_open_multipart('blog/uploadimg');?>
    

    【讨论】:

    • 不,我没有使用表单标签。这是我的看法->>>>>
      assest/img/blank.png" alt="空白图片" id="uploadimg" class="img-thumbnail">
    【解决方案3】:

    如果你在 javascript 中使用这个插件(写得很好),你可以获得无缝的功能。

    http://malsup.com/jquery/form/

    在 PHP 中上传文件

    <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["file"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["file"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>
    

    【讨论】:

    • 如果这可以满足您的需求,您为什么还要寻找另一个?
    • 我看到了你的例子,但是在这个例子中页面是刷新的,但我不想在上传图片时刷新页面。这就是我使用 jquery 的原因
    • 我想你还没有完全探索它。去这里malsup.com/jquery/form/progress.html
    • 好的,我使用这个例子,但我有一个困惑,我如何在我的控制器中获取请求,当我使用 $_FILE 时出现这样的错误。
    • 朋友,你需要学习你正在使用的框架的基础知识。
    【解决方案4】:

    您可以使用Ajaxfileupload.js上传文件:

    $('input[type="file"]').ajaxfileupload({
              'action': 'save_photo.php',
              'params': {
                'extra': 'info'
              },
              'onComplete': function(response) {
    
               console.log('custom handler for file:');
               alert(JSON.stringify(response));
    
              },
              'onStart': function() {               
    
              },
              'onCancel': function() {
                console.log('no file selected');
              }
        });
    

    保存照片.php:

    <?php
    
    print_r($_FILES); // print details about the file which has been uploaded
    
    ?>
    

    【讨论】:

    • 此 API 无法正常工作。当我使用此 API 时会显示一些错误。
    • 它工作得很好我用过同样的..你遇到了什么错误?
    • 当我使用 jquery.ajaxfileupload.js 文件时。我在控制台中收到错误消息“Uncaught SyntaxError: Unexpected token
    猜你喜欢
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2012-05-29
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多