繁体   English   中英

如何使用Ajax上传多张图片?

[英]How to upload multiple image with Ajax?

我有一个使用Kohana框架的网站。 尝试使用AJAX上传多张图片时出现问题。 我尝试了很多方法,但没有成功。 我认为问题出在函数_save_images($image)中:

if ($file = Upload::save($image, NULL, $directory))

因为我尝试echo此值,但收到如下结果:

网站不支持宽度小于900px的计算机

使用参数$image保存图像的功能是数组列表图像。

ProductImage.php

protected function _save_images($image)
{
    $directory = DOCROOT.'uploads/';

    if ($file = Upload::save($image, NULL, $directory))
    {
        $filename = strtolower(Text::random('alnum', 20)).'.jpg';

        Image::factory($file)
            ->resize(200, 200, Image::AUTO)
            ->save($directory.$filename);

        // Delete the temporary file
        unlink($file);

        return $filename;
    }
}

而且我有一个上传多张图片的功能。

public function action_create()
{
    $user = Auth_Jelly::instance()->get_user();  
    $iduser = $user->id;
    if($user->has_role('admin') || $user->check_permission($iduser,'CREATE_PRODUCT')==1){
    $this->auto_render = false;
    if(Request::$is_ajax)
    {
        $name_img = Security::xss_clean($_POST['name_img']);
        $type_img = Security::xss_clean($_POST['type_img']); 
        $size_img = Security::xss_clean($_POST['size_img']); 

        $new_array = array();
        foreach($name_img as $item){
            $new_array['name'][] = $item;
        }
        foreach($type_img as $item){
            $new_array['type'][] = $item;
        }
        foreach($size_img as $item){
            $new_array['size'][] = $item;
        }

        $files = $new_array;
        unset($new_array);
        $ilosc = count($files['name'])-1;
        for($i=0; $i<=$ilosc; $i++) {        
            $_FILES['image_list'.$i]['name'] = $files['name'][$i];
            $_FILES['image_list'.$i]['type'] = $files['type'][$i];
            $_FILES['image_list'.$i]['size'] = $files['size'][$i];
            $array_new[] = array(
                'name'=>$_FILES['image_list'.$i]['name'],
                'type'=>$_FILES['image_list'.$i]['type'],
                'error'=>0,
                'size'=>$_FILES['image_list'.$i]['size'],
                );
        }

        foreach ($array_new as $key => $value) {
            $this->_save_images($value);
            if($this->save_images($value)==FALSE){
                echo "Faild Upload";
            }else{
                echo "Upload Success";
            }
        }
    }
    }else{
     // Request::current()->redirect('admin/home/denied');  
    }
}

ProductImage.js

$("#"+form).click(function(){   

var image_list = Array();
var imageFiles = document.getElementById("image_list"),
    filesLength = imageFiles.files.length;
    for (var i = 0; i < filesLength; i++) {
      image_list[i] = imageFiles.files[i].name;
    }


var myFileList = document.getElementById('image_list').files;
var file ;
var name_img= Array();
var type_img= Array();
var size_img= Array();
// loop through files
for (var i = 0; i < myFileList.length; i++) {

    // get item
    file = myFileList.item(i);
    //or
    file = myFileList[i];
    name_img[i]= file.name;
    type_img[i]= file.type;
    size_img[i]= file.size;
}


var local = window.location;
var val_content = tinyMCE.editors[0].getContent();
var language = $.trim($('#product-create-language option:selected').val()); 
var category = $.trim($('input[name=category]').val());
var status = $.trim($('input[name=createstatus]:checked').val());
var position = $.trim($('input[name=createposition]:checked').val());

var matches = [];
$(".addcheck:checked").each(function() {
    matches.push(this.value);
});
if(matches.length>0)
    matches=matches;
else
    matches=null;
if(validateSpace(title,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",titleinfo) && validateSpace(image,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imageinfo) && validateSpace(imagebig,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagebiginfo) && validateSpace(imagemobile,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagemobileinfo) && validateSpace(keywords,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",keywordsinfo) && validateSpace(description,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",descriptioninfo) && validateSpace(date,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",dateinfo)){
        var data = {name_img:name_img,type_img:type_img,size_img:size_img,category:category,mycolor: matches,language:language,title:$("#"+title).val(),image:$("#"+image).val(),imagebig:$("#"+imagebig).val(),imagemobile:$("#"+imagemobile).val(),fileupload:$("#"+fileupload).val(),price:$("#"+price).val(),pricesale:$("#"+pricesale).val(),idproduct:$("#"+idproduct).val(),color:$("#"+color).val(),packing:$("#"+packing).val(),cbmpsc:$("#"+cbmpsc).val(),size:$("#"+size).val(),container:$("#"+container).val(),excerpt:$("#"+excerpt).val(),content:val_content,keywords:$("#"+keywords).val(),description:$("#"+description).val(),date:$("#"+date).val(),status:status,position:position};
        $(".product-content-create-total").fadeOut(); // hidden div content field register // children div of div class //register-form-center\\
        $(".product-content-create").css("height","auto"); // set height/auto after hidden div class //register-form-center\\
        $(".product-content-create-alert").html(""); // remove text div alert register // parent div of div id //register-form-content\\
        $(".product-content-create-alert").css("margin-bottom","25px");
        $(".product-content-create-alert").fadeIn("slow");
        $(".product-content-create-alert").html('<img src="'+base_url+'themes/admin/images/loader.gif" alt="loader">');
        $.ajax({
        url: admin_url +"product/create",
        type: "POST",
        data: data,
        cache: false,
        success: function(html) {
            console.log(html);
        }
    });
}else{
    return false;
}
});
});

似乎有很多代码,所以,我希望任何人都可以帮助我。

更新:

在这里,我的表单代码包括“提交”按钮:

<form enctype="multipart/form-data" name="form-product-create" method="post">
    <input type="file"  id="image_list" name="image_list[]" multiple>
    <input type="button" name="btnproductcreateclick" value=" " id="btn-product-create-click" style="margin-left:119px;" class="form-btn-create-click" />
</form>

的HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
        <input name="file[]" type="file" />
        <button class="add_more">Add More Files</button>
        <input type="button" value="Upload File" id="upload"/>
</form>

Java脚本

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

的PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

阿贾克斯

$('body').on('click', '#upload', function(e){
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                alert("Data Uploaded: "+data);
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
})

资料来源: 如何使用PHP,jQuery和AJAX上传多个文件

在您的代码错误看起来像在附近,

foreach ($array_new as $key => $value) {
        $this->_save_images($value);
        if($this->save_images($value)==FALSE){
            echo "Faild Upload";
        }else{
            echo "Upload Success";
        }
}

当您调用$this->_save_images($value); 您不保存上传图像的文件名。 $file_name = $this->_save_images($value); 然后保存此$file_name

foreach ($array_new as $key => $value) {
            $file_name= $this->_save_images($value);
            if($this->save_images($file_name)==FALSE){
                echo "Faild Upload";
            }else{
                echo "Upload Success";
            }
}

HTML表单必须具有带有“ post”值的“ method”属性。 因为只有在表单的method属性值为post时文件才会发送到服务器。

<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
    <input type="hidden" name="image_form_submit" value="1"/>
        <label>Choose Image</label>
        <input type="file" name="images[]" id="images" multiple >
    <div class="uploading none">
        <label> </label>
        <img src="uploading.gif"/>
    </div>
</form>

的PHP

演示版

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM