簡體   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