Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 在ajax和codeigniter中插入带有上载图像的数据_Jquery_Ajax_Codeigniter - Fatal编程技术网

Jquery 在ajax和codeigniter中插入带有上载图像的数据

Jquery 在ajax和codeigniter中插入带有上载图像的数据,jquery,ajax,codeigniter,Jquery,Ajax,Codeigniter,代码如下所示 查看 <input type="text" name="name" id="name" class="input_field" /> <input type="file" name="userfile" id='img_upload' /> 但是当我提交表单时,我可以看到错误消息是“您没有选择要上载的文件” 如何通过ajax插入带有上载图像的数据 有什么需要帮忙的吗 您不能像这样上传图像,请使用插件通过ajax上传图像。您需要使用ajax表单上传,

代码如下所示

查看

<input type="text" name="name" id="name" class="input_field" />    
<input type="file" name="userfile" id='img_upload' />
但是当我提交表单时,我可以看到错误消息是“您没有选择要上载的文件”

如何通过ajax插入带有上载图像的数据


有什么需要帮忙的吗

您不能像这样上传图像,请使用插件通过ajax上传图像。

您需要使用ajax表单上传,您可以使用插件通过ajax上传图像。

我正在使用插件

HTML:

    <form method="post" action="" id="company_logo">
        <input type="file" class="clsField" name="company_image" id="company_image"/>
        <input type="submit" name="submit" id="submit" />
    </form>
控制器:

        $('#company_logo').submit(function(e) {
        e.preventDefault();
        $.ajaxFileUpload({
            url         : '../users/uploadFile',
            secureuri      :false,
            fileElementId  :'company_image',
            dataType: 'json',
            data:  {'name' : 'company-avatar'},
            success  : function (data, status)
            {
                // You have link to image inside data.file
            }
        });
        return false;
        });
/**
 * uploadFile - ajax response function for file upload
 * @param none - gets post
 * @return file url
 **/
public function uploadFile() {
    $input = $this->input->get_post('name');
    if($input) {
        if($input == 'company-avatar') {
            echo json_encode(array('file' => $this->***_users_model->uploadFile($_FILES['company_image'])));
        }
    }
}
/**
 * uploadFile
 * @param $file - $_FILES array, $type - type of file to upload
 * @return path to file
 **/
public function uploadFile($file, $type = 'images') {
    $username = $this->session->userdata('username');
    $fileName = $file['name'];
    $fileData = $file['tmp_name'];
    if(empty($file['name']) || empty($file['tmp_name'])) {
        return;
    }

    $fileDir = "your path";
    $fileDir .= "/$type";

    $filePath = "$fileDir/$fileName";

    //Creating dir if doesn't exists.
    if (!file_exists($fileDir)) {
        mkdir($fileDir, 0777, true);
    }
    move_uploaded_file($fileData, $filePath);

    return $filePath;
}
型号:

        $('#company_logo').submit(function(e) {
        e.preventDefault();
        $.ajaxFileUpload({
            url         : '../users/uploadFile',
            secureuri      :false,
            fileElementId  :'company_image',
            dataType: 'json',
            data:  {'name' : 'company-avatar'},
            success  : function (data, status)
            {
                // You have link to image inside data.file
            }
        });
        return false;
        });
/**
 * uploadFile - ajax response function for file upload
 * @param none - gets post
 * @return file url
 **/
public function uploadFile() {
    $input = $this->input->get_post('name');
    if($input) {
        if($input == 'company-avatar') {
            echo json_encode(array('file' => $this->***_users_model->uploadFile($_FILES['company_image'])));
        }
    }
}
/**
 * uploadFile
 * @param $file - $_FILES array, $type - type of file to upload
 * @return path to file
 **/
public function uploadFile($file, $type = 'images') {
    $username = $this->session->userdata('username');
    $fileName = $file['name'];
    $fileData = $file['tmp_name'];
    if(empty($file['name']) || empty($file['tmp_name'])) {
        return;
    }

    $fileDir = "your path";
    $fileDir .= "/$type";

    $filePath = "$fileDir/$fileName";

    //Creating dir if doesn't exists.
    if (!file_exists($fileDir)) {
        mkdir($fileDir, 0777, true);
    }
    move_uploaded_file($fileData, $filePath);

    return $filePath;
}
另外,我不知道我的解决方案是否足够好,但它对我来说是可行的,请注意ajaxFileUpload使用的jQuery handleError已被弃用,因此您应该添加此函数:

 handleError: function( s, xhr, status, e ) {
    // If a local callback was specified, fire it
    if ( s.error ) {
        s.error.call( s.context || window, xhr, status, e );
    }

    // Fire the global callback
    if ( s.global ) {
        (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
    }
}

您仍然可以只使用ajax,这就足够了。 但您必须在表单数据中正确地附加图像

因为“.serialize()”方法创建标准URL编码表示法的文本字符串,而不是MIME数据

<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />

我希望这能奏效

<script>
   var client = new XMLHttpRequest();

   function upload() 
   {
      var file = document.getElementById("uploadfile");

      /* Create a FormData instance */
      var formData = new FormData();
      /* Add the file */ 
      formData.append("upload", file.files[0]);

      client.open("post", "/upload", true);
      client.setRequestHeader("Content-Type", "multipart/form-data");
      client.send(formData);  /* Send to server */ 
   }

   /* Check the response status */  
   client.onreadystatechange = function() 
   {
      if (client.readyState == 4 && client.status == 200) 
      {
         alert(client.statusText);
      }
   }
</script>

var client=new XMLHttpRequest();
函数上传()
{
var file=document.getElementById(“上传文件”);
/*创建一个FormData实例*/
var formData=new formData();
/*添加文件*/
formData.append(“上传”,file.files[0]);
client.open(“post”、“/upload”、true);
setRequestHeader(“内容类型”、“多部分/表单数据”);
client.send(formData);/*发送到服务器*/
}
/*检查响应状态*/
client.onreadystatechange=函数()
{
if(client.readyState==4&&client.status==200)
{
警报(client.statusText);
}
}

在这段代码“formData.append(“upload”,file.files[0]);”中,用PHP控制器变量名替换“upload”

使用ajaxForm,使用ajax上传图像-使用此
var formData=new formData(此)
而不是这个
dataString=$(“#学生信息表格”).serialize()
将数据发送到控制器。