我一直坚持这个问题很长一段时间,并决定寻求帮助。这似乎不是一个应该让我如此沮丧的问题,但我无法弄清楚这一点。
我正在尝试使用CodeIgniter和AJAX从表单上传文件。任何建议都会很棒。谢谢!
查看:
<form method='post' enctype='multipart/form-data'>
<label>Name</label>
<input type='text' id='ImageName' class='form-control' /><br />
<label>Image</label>
<input type='file' name='userfile' id='userfile' />
<button type='button' class='btn btn-success extend-btn' id='UploadSaveButton'>Add Materials</button>
</form>
JS
$(document.body).on('click', '#UploadSaveButton', function(){
var Name = $("#ImageName").val();
var Image = new FormData($("#userfile").val());
$.ajax({
url: '/Store/SaveImage',
type: 'POST',
processData: false,
contentType: false,
fileElementId: 'userfile',
dataType: 'json',
data: {Name:Name, Image:Image},
success:function(response){
var data = JSON.parse(response);
if(data && data.error_message && data.error_message!="") {
$("#UploadError").html(data.error_message);
} else {
//success
}
},
error:function(){
$("#UploadError").html("An error occured. Try again later.");
}
});
});
控制器
public function SaveImage()
{
$config['upload_path'] = base_url().'uploads/PrimaryImages/';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['max_size'] = 1024;
$config['max_width'] = 5000;
$config['max_height'] = 5000;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile')) {
$data = array(
'error_message' => $this->upload->display_errors()
);
} else {
$data['upload_data'] = $this->upload->data();
}
$this->output->set_output(json_encode ($data));
}
无论我做什么,Json的回复总是&#34;你没有选择要上传的文件。&#34;
答案 0 :(得分:2)
保持简单:
上传表单
<form class="ui form" method="post" id="uploadForm" enctype="multipart/form-data">
<div class="ui form">
<div class="field required ">
<label>Bonus Amount</label>
<input name="userfile" id="userfile" placeholder="Bonus Amount" type="file" ></div>
<button name="action" class="ui button" id="upload" value="Upload">Upload Image</button>
</div>
</form>
你的ajax:
<script >
$(document).ready(function(e) {
$('#upload').on('click' , function () {
$.ajax({
url : '<?php echo base_url().'admin/uploadImage' ?>',
type : 'post',
data: $('#uploadForm').serialize(),
success : function(response) {
console.log(response);
}
});});
});
</script>
控制器:
public function uploadImage() {
if($this->input->post('action') == 'Upload') {
$data = array();
$config['upload_path'] = APPPATH.'uploads'.DIRECTORY_SEPARATOR;
$config['allowed_types'] = '*';
$config['max_size'] = 1024;
$config['max_width'] = 5000;
$config['max_height'] = 5000;
print_r($config);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile')) {
$data = array('error_message' => $this->upload->display_errors());
} else {
$data['upload_data'] = $this->upload->data();
}
print_r($data);
die;
}
}
答案 1 :(得分:0)
经过进一步研究,我发现在不使用iFrame的情况下,无法通过AJAX调用发送图像。老实说,我不相信,我相信有办法。无论如何,无济于事,我得到了一个插件。 http://filer.grandesign.md/