我有一个教程中的代码,我不知道发生了什么,为什么我的工作不起作用。我只是按照教程,代码不起作用。我正在使用codeigniter框架,请帮助我这些,我在控制台也没有错误,我不知道发生了什么原因。它也不会从ajax发送请求。请检查ajax中的代码。感谢。
ajax代码:
$(function () {
var inputFile = $('input[name=file]');
var uploadURI = $('#form-upload').attr('action');
$('#upload-btn').on('click', function(event) {
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData();
formData.append("file", fileToUpload);
$.ajax({
url: uploadURI,
type: "POST",
data: formData,
processData: false,
contentData: false,
success: function(data) {
alert("Profile picture updated!");
}
});
}
});
});
来自视图:
<form action="<?php echo site_url("profile/profile_picture") ?>" id="form-upload">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput"><i class="glyphicon glyphicon-file fileinput-exists"></i> <span class="fileinput-filename"></span></div>
<span class="input-group-addon btn btn-default btn-file"><span class="fileinput-new"><i class="glyphicon glyphicon-paperclip"></i> Select file</span><input type="file" name="file"></span>
<a href="#" id="upload-btn" class="input-group-addon btn btn-success fileinput-exists"><i class="glyphicon glyphicon-open"></i> Upload</a>
</div>
</form>
控制器:
public function profile_picture() {
$config['upload_path'] = "./assets/uploaded_images/";
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
}
else {
echo "File cannot be uploaded";
}
}
File cannot be uploadedarray(1) {
["error"]=>
string(43) "<p>You did not select a file to upload.</p>"
}
答案 0 :(得分:2)
好的问题是它应该是&#39; contentType
&#39;不是contentData
&#39;。这是更新的JS代码
$(function () {
var inputFile = $('input[name=file]');
var uploadURI = $('#form-upload').attr('action');
$('#upload-btn').on('click', function(event) {
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: uploadURI,
data: formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Profile picture updated!");
}
});
}
});
});
答案 1 :(得分:0)
你可以通过我的线程,我给出了使用ajax上传多个图像的解决方案,它很容易从我的解决方案名称中删除数组,然后你将在控制器中获取你的图像。
这是我的解决方案的链接。 getting error while uploading image via Ajax