当前位置: 首页 > 面试题库 >

用jquery ajax上传多个图像并用php处理它们

阳念
2023-03-14
问题内容

我以前从未做过这样的事情,我在问如何做。我可以找到如何使用纯html格式的表单等来执行此操作。但是现在如何使用ajax来执行此操作?

伪代码:

的HTML:

<input type="text" class="imgform" name="imagename" value="name" />
<input type="file" class="imgform_image" name="image" value="C:\Users\william\Pictures\image.png" />
<input type="button" id="btn" form="imgform" />

JQUERY:

$('body').on('click', '#btn', function(){
    var form = $(this).attr("form");
    var string = $('.' + form).serialize();

    var image = $('.imgform_image').value("form");
    image = converttobase64(image);

    $.post('action.php?action=uploadimg', string + {'image':image}, function (data){    
       datalader(data);
    });
});

不知道如何执行此操作。还有一种方法可以对多个img文件执行此操作,并检查该文件实际上是否是图像,并且当然使用文件名作为图像名称,而不是使用输入文本字段。

任何提示,链接或代码示例都将非常有用,谢谢!


问题答案:

注意:我完全审查了我的答案,并使其变得更好!

的HTML

首先,我们制作没有确认按钮的传统表格。相反,我们做了一个按钮。

<form enctype="multipart/form-data" id="myform">    
    <input type="text" name="some_usual_form_data" />
    <br>
    <input type="file" accept="image/*" multiple name="img[]" id="image" /> <sub>note that you have to use [] behind the name or php wil only see one image</sub>
    <br>
    <input type="button" value="Upload images" class="upload" />
</form>
<progress value="0" max="100"></progress>
<hr>
<div id="content_here_please"></div>

Javascript / jquery上传端

比这是Javascript。。o是,并使用Jquery上传图像和其他表单数据

    $(document).ready(function () { 
        $('body').on('click', '.upload', function(){
            // Get the form data. This serializes the entire form. pritty easy huh!
            var form = new FormData($('#myform')[0]);

            // Make the ajax call
            $.ajax({
                url: 'action.php',
                type: 'POST',
                xhr: function() {
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){
                        myXhr.upload.addEventListener('progress',progress, false);
                    }
                    return myXhr;
                },
                //add beforesend handler to validate or something
                //beforeSend: functionname,
                success: function (res) {
                    $('#content_here_please').html(res);
                },
                //add error handler for when a error occurs if you want!
                //error: errorfunction,
                data: form,
                // this is the important stuf you need to overide the usual post behavior
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });

    // Yes outside of the .ready space becouse this is a function not an event listner!
    function progress(e){
        if(e.lengthComputable){
            //this makes a nice fancy progress bar
            $('progress').attr({value:e.loaded,max:e.total});
        }
    }

PHP处理方面

对于那些需要php端对这些图像进行处理的人,这里是php循环槽的代码:

<?php

    $succeed = 0;
    $error = 0;
    $thegoodstuf = '';
    foreach($_FILES["img"]["error"] as $key => $value) {
        if ($value == UPLOAD_ERR_OK){
            $succeed++;

            // get the image original name
            $name = $_FILES["img"]["name"][$key];

            // get some specs of the images
            $arr_image_details = getimagesize($_FILES["img"]["tmp_name"][$key]); 
            $width = $arr_image_details[0];
            $height = $arr_image_details[1];
            $mime = $arr_image_details['mime'];

            // Replace the images to a new nice location. Note the use of copy() instead of move_uploaded_file(). I did this becouse the copy function will replace with the good file rights and  move_uploaded_file will not shame on you move_uploaded_file.
            copy($_FILES['img']['tmp_name'][$key], './upload/'.$name);

            // make some nice html to send back
            $thegoodstuf .= "
                                <br>
                                <hr>
                                <br>

                                <h2>Image $succeed - $name</h2>
                                <br>
                                specs,
                                <br>
                                width: $width  <br>
                                height: $height <br>
                                mime type: $mime <br>
                                <br>
                                <br>
                                <img src='./upload/$name' title="$name" />
            ";
        }
        else{
            $error++;
        }
    }

    echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';

    if($error){
        echo 'shameful display! '.$error.' images where not properly uploaded!<br>';
    }

    echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];

    echo $thegoodstuf;

?>

我的开发Web服务器上的实时演示并不总是在线的!

如果要压缩和调整大小

您需要此类:

class SimpleImage{

        var $image; 
        var $image_type;

        function load($filename){   
            $image_info = getimagesize($filename); 
            $this->image_type = $image_info[2];

            if($this->image_type == IMAGETYPE_JPEG)
            {   
                $this->image = imagecreatefromjpeg($filename); 
            }
            elseif($this->image_type == IMAGETYPE_GIF) 
            {   
                $this->image = imagecreatefromgif($filename); 
            }
            elseif($this->image_type == IMAGETYPE_PNG)
            {   
                $this->image = imagecreatefrompng($filename); 
            }
        }

        function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=0777){

            if($image_type == IMAGETYPE_JPEG)
            { 
                $gelukt = imagejpeg($this->image,$filename,$compression); 
            }
            elseif($image_type == IMAGETYPE_GIF)
            {   
                $gelukt = imagegif($this->image,$filename); 
            }
            elseif($image_type == IMAGETYPE_PNG)
            {   
                $gelukt = imagepng($this->image,$filename); 
            }

            if($permissions != false)
            {   
                chmod($filename,$permissions); 
            }

            return $gelukt; 
        }

        function output($image_type=IMAGETYPE_JPEG) {

            if($image_type == IMAGETYPE_JPEG)
            { 
                imagejpeg($this->image); 
            } 
            elseif($image_type == IMAGETYPE_GIF) 
            {   
                imagegif($this->image); 
            }
            elseif($image_type == IMAGETYPE_PNG)
            {   
                imagepng($this->image); 
            } 
        }

        function getWidth(){

            return imagesx($this->image);

        }

        function getHeight(){

            return imagesy($this->image);

        }

        function maxSize($width = 1920, $height = 1080){
            if(($this->getHeight() > $height) && ($this->getWidth() > $width)){
                $ratio = $height / $this->getHeight(); 
                $newwidth = $this->getWidth() * $ratio;

                if($newwidth > $width){
                    $ratio = $width / $newwidth; 
                    $height = $height * $ratio;
                    $newwidth = $width;
                }

                $this->resize($newwidth,$height);
                return true;
            }
            elseif($this->getHeight() > $height){
                $ratio = $height / $this->getHeight(); 
                $width = $this->getWidth() * $ratio;

                $this->resize($width,$height);
                return true;
            }
            elseif($this->getWidth() > $width){
                $ratio = $width / $this->getWidth(); 
                $height = $this->getheight() * $ratio;

                $this->resize($width,$height);
                return true;
            }
            return false;
        }

        function resizeToHeight($height){   
            $ratio = $height / $this->getHeight(); 
            $width = $this->getWidth() * $ratio; 
            $this->resize($width,$height); 
        }

        function resizeToWidth($width){ 
            $ratio = $width / $this->getWidth(); 
            $height = $this->getheight() * $ratio; 
            $this->resize($width,$height); 
        }

        function scale($scale){ 
            $width = $this->getWidth() * $scale/100; 
            $height = $this->getheight() * $scale/100; 
            $this->resize($width,$height); 
        }

        function resize($width,$height) {

            $new_image = imagecreatetruecolor($width, $height); 
            if( $this->image_type == IMAGETYPE_GIF || $this->image_type == IMAGETYPE_PNG )
            { 
                $current_transparent = imagecolortransparent($this->image);

                if($current_transparent != -1) {
                    $transparent_color = imagecolorsforindex($this->image, $current_transparent); 
                    $current_transparent = imagecolorallocate($new_image, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); 
                    imagefill($new_image, 0, 0, $current_transparent); 
                    imagecolortransparent($new_image, $current_transparent); 
                }
                elseif($this->image_type == IMAGETYPE_PNG)
                { 
                    imagealphablending($new_image, false); 
                    $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127); 
                    imagefill($new_image, 0, 0, $color); 
                    imagesavealpha($new_image, true);


            } 
        }

        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); 
        $this->image = $new_image;   
    }
}

您可以像这样使用它:

$succeed = 0;
$error = 0;
$thegoodstuf = '';
foreach($_FILES["img"]["error"] as $key => $value) {
    if ($value == UPLOAD_ERR_OK){
        $succeed++;

        $name = $_FILES["img"]["name"][$key];

        $image = new SimpleImage();
        $image->load($_FILES['img']['tmp_name'][$key]); 
        $chek = $image->maxSize();

        if($chek){
            $move = $image->save('./upload/'.$name);
            $message= 'Afbeelding verkleind naar beter formaat!<br>';
        }
        else{
            $move = copy($_FILES['img']['tmp_name'][$key], './upload/'.$name);
            #$move = move_uploaded_file($_FILES['img']['tmp_name'][$key], './upload/'.$name);
            $message= '';
        }

        if($move){

            $arr_image_details = getimagesize('./upload/'.$name); 
            $width = $arr_image_details[0];
            $height = $arr_image_details[1];
            $mime = $arr_image_details['mime'];

            $thegoodstuf .= "
                            <br>
                            <hr>
                            <br>

                            <h2>Image $succeed - $name</h2>
                            <br>
                            specs,
                            <br>
                            $message
                            width: $width  <br>
                            height: $height <br>
                            mime type: $mime <br>
                            <br>
                            <br>
                            <img src='./upload/$name' title="$name" />
            ";
        }
        else{
            $error++;
        }
    }
    else{
        $error++;
    }
}

echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';

if($error){
    echo 'shameful display! '.$error.' images where not properly uploaded!<br>';
}

echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];

echo $thegoodstuf;


 类似资料:
  • 问题内容: 使用AJAX上传多张图片时遇到很多问题。我写这段代码: 的HTML jQuery / AJAX 我尝试了各种版本,但从未成功通过ajax发送多个数据。我已经按照这种方式尝试了以上所见,现在我仅获得POST信息。我知道为什么会收到POST,但我需要发送FILES信息,而且我不知道我哪里写错了。 我不是第一次使用Ajax,经常在大多数项目中使用它,但是我从未使用过发送多个文件,这现在困扰着

  • 问题内容: 我想使用PHP上传文件,但问题是我不知道要上传多少文件。 我的问题是,如果使用该如何上传文件? 我将仅添加“文件”框,并使用JavaScript创建更多要上传的文件输入,但是如何在PHP中处理它们呢? 问题答案: 请参阅:$ _FILES ,处理文件上传

  • 主要内容:GD 库PHP 提供了丰富的图像处理函数,主要包括: 函数 描述 gd_info() 取得当前安装的 GD 库的信息 getimagesize() 获取图像信息 getimagesizefromstring() 获取图像信息 image_type_to_extension() 获取图片后缀 image_type_to_mime_type() 返回图像的 MIME 类型 image2wbmp() 输出WBM

  • 问题内容: 我对jQuery和Ajax函数还比较陌生,但是过去几天一直在使用Ajax表单。我在尝试上传图像时遇到文件上传问题。在寻找资源时,我找不到任何有用的东西,因为它们似乎过于复杂,毫无意义,没有任何解释,这无助于我进一步学习。 我已经编写了以下代码来处理Ajax中的图片上传: 这向文件发送了一个请求,但是没有发送数据,基本上我的表单实际上是这样的: 似乎没有任何数据在标头中传递,我认为我将通

  • 一旦用户点击掩码映像,我们就允许用户上传自定义映像,如果只有一个掩码映像:https://codepen.io/kidsdial/pen/jjbvon就可以正常工作 要求: 但是如果有多个掩码映像,那么用户也应该能够上传所有掩码映像上的自定义映像[类似https://codepen.io/kidsdial/pen/rrmypr],但是现在它只适用于单个映像.... 2图像代码页:https://c

  • 一旦用户点击掩码映像,我们就允许用户上传自定义映像,如果只有一个掩码映像:https://codepen.io/kidsdial/pen/jjbvon就可以正常工作 要求: 但是如果有多个掩码映像,那么用户也应该能够上传所有掩码映像上的自定义映像[类似https://codepen.io/kidsdial/pen/rrmypr],但是现在它只适用于单个映像.... 2图像代码页:https://c