0

我要做的就是使用 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>
4

1 回答 1

1

不应该是:

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

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

于 2012-11-08T01:42:15.187 回答