我要做的就是使用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>
答案 0 :(得分:1)
不应该是:
formdata.append("imagetoresize",imgfile.file);
请参阅https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects