【问题标题】:Why, when uploading files via Ajax, is CodeIgniter throwing a "no file uploaded" error?为什么通过 Ajax 上传文件时,CodeIgniter 会抛出“没有文件上传”错误?
【发布时间】:2012-10-28 04:25:19
【问题描述】:

我要做的就是使用 ajax 将文件上传到基于 CodeIgniter 的网站。但由于某种原因,CodeIgniter 不断给出“没有上传文件”错误。我该如何解决这个问题?

这里是 JavaScript:

<script type="text/javascript">
function updatebgimage()
    {   
        regexp = /^[^[\]]+/;
        var imgfile = document.getElementById("imagetoresize"); 
        var fileInputName = regexp.exec( imgfile['name'] ); 
        formdata = new FormData(); 
        formdata.append("imagetoresize",imgfile.files[0]);
        $.ajax({  
            url: "<?php echo site_url('uploadbgimage'); ?>",  
            type: "POST",  
            data: formdata,  
            dataType: "json",
            processData: false,  
            contentType: false,  
            success: function (data) {  
                    alert(data.message); 
            }  
        });  
    } 
</script>

这里是被调用的 CodeIgniter 控制器:

public function uploadbgimage()
{
    $config['upload_path'] = './images/stores/'.$memberid.'/'; 
    $config['file_name'] = 'main_bg_image.jpg'; 
    $config['allowed_types'] = 'jpg|png'; 
    $config['overwrite'] = true;       
    $this->load->library('upload', $config);  
    $data = array();
    if (! $this->upload->do_upload("bgimage"))
    {
        $data['result'] = 'fail';
    $data['message'] = $this->upload->display_errors();  
    } 
    else 
    {
         $data['result'] = 'success';
     $data['message'] = 'file was uploaded fine';  
    }
    echo json_encode($data);
}

这是 HTML:

<form method="post" enctype="multipart/form-data">
     <input type="file" id="imagetoresize" name="imagetoresize" value="" class="field1" /> 
     <input type="button" onclick="updatebgimage()" value="UploadBGImage" /> 
</form>

【问题讨论】:

  • 好的,我把它放进去,它仍然没有工作......
  • 我们的编辑发生了冲突。给我一秒钟...好的,已修复。
  • 上传数据实际传递到哪里?
  • 我在 codeigniter 上构建这个网站,并将它发送到一个控制器,其路由在路由文件中定义并正确。

标签: php jquery ajax codeigniter file-upload


【解决方案1】:

不应该是:

formdata.append("imagetoresize",imgfile.file);

https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects

【讨论】:

  • 是的,我试过不格式化图像文件字段,但这也没有用。
  • 表单数据是pair key-value,key应该是你的表单文件字段名,也不是文件名
猜你喜欢
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2016-04-16
  • 2015-12-26
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 2015-12-30
相关资源
最近更新 更多