我需要使用ajax将文件(从表单)和其他数据“发送”到codeigniter控制器。像这样:
$("#formuploadajax").on("submit", function(e){
e.preventDefault();
var f = $(this);
var formData = new FormData(document.getElementById("formuploadajax"));
formData.append("dato", "valor");
//formData.append(f.attr("name"), $(this)[0].files[0]);
$.ajax({
url: "example/examplerecibe.php",
type: "post",
dataType: "html",
data: formData,
cache: false,
contentType: false,
processData: false
})
.done(function(res){
$("#mensaje").html("Respuesta: " + res);
});
});
...
codeigniter控制器验证文件和其他数据,然后在相应的文件夹中创建文件。
我尝试使用stackoverflow和其他网站上的大量代码,但对我来说没有任何作用。
答案 0 :(得分:0)
经过多次尝试,这对我有用。
我推送所有代码(html,js y the controller -php - ):
视图和脚本:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
<script type="text/javascript">
var pathArray = "<?php print base_url(); ?>";
</script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function submitFile(){
var formUrl = "url of your php";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url:pathArray+'creacion/crearSolicitud/do_upload',
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert("bien");
},
error: function(jqXHR){
// var result = JSON.parse(query);
alert("mal");
}
});
}
</script>
</body>
</html>
和CodeIgniter:
public function do_upload()
{
//Condicion de que sea una entrada tipo AJAX:
if(!$this->input->is_ajax_request())
{
echo json_encode("jaja");
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
//$config['max_size'] = '1000000';
//$config['max_width'] = '10240';
//$config['max_height'] = '768000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
echo json_encode($data);
}
有了这个,我可以创建一个不刷新页面的文件,只发送一条消息。
答案 1 :(得分:0)
我已经实现了
function uploadfile() {
var input = document.getElementById("photoid");
file = input.files[0];
if (file != undefined) {
formData = new FormData();
if (!!file.type.match(/image.*/)) {
formData.append("image", file);
$('#loader').fadeIn();
$.ajax({
url: "http://example.com",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {
$("#loader").fadeOut(1000);
if (data == 1) {
//success
}
else {
//error
}
}
});
} else {
alert('Please select an image');
}
} else {
alert('Please Select Image!');
}
} ;