通过ajax传递一个图像,通过表单传递另一个图像

时间:2019-07-23 07:03:31

标签: javascript php jquery server image-uploading

我是Onclick按钮,正在尝试保存2张不同的图像。

我正在通过 ajax 传递一个图像,并通过 form 传递另一个图像,但是我一次只能下载一个图像。会造成任何冲突吗?

两个图像都需要具有正确的Content-Length标头吗?

HTML

<div id="target">
<div id="container" class="container"></div>
</div>

<input type="submit" value="Save" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
    <input type="hidden" name="img_val" id="img_val" value="" />
</form>   

脚本

function capture() 
{
    // one image
    var canvas = document.getElementById("1");
    var dataURL = canvas.toDataURL(); // THE BASE 64 DATA
    var dataFileName = document.getElementById('fileup').value.replace(/.*(\/|\\)/, ''); // GET THE FILE NAME THAT USER CHOSE
    var dataFileType = dataFileName.split('.').pop();
    data = new FormData();
    data.append('imgBase64', file, file.name);

    $.ajax({
        type: "POST",
        url: "save.php",
        cache:false,
        contentType: false,
        processData: false,
        data: data
    }).done(function(o) {
        var response = JSON.parse(o);
        $('body').prepend('<img src="/var/www/html/ecom1/site/test/final/' + response.data[0].fileName + '" style="height: 200px; width: auto;">');
    });

     //another image
    $('#target').html2canvas({
        onrendered: function (canvas) {
            //Set hidden field's value to image data (base-64 string)
            $('#img_val').val(canvas.toDataURL("image/png"));
            //Submit the form manually
            document.getElementById("myForm").submit();
        }
    });     
}

php

<?php

// One image code : 

if (isset($_FILES['imgBase64'])) 
{
    $fname   = $_FILES["imgBase64"]["name"]; // THE FILENAME THE USER CHOSE IS RECEIVED VIA POST
    $img     = filter_input(INPUT_POST, 'imgBase64'); // THE BASE64 ENCODING RECEIVED VIA POST
    $imgtype = $_FILES["imgBase64"]["type"]; // THE FILE TYPE / EXTENSION IS RECEIVED VIA POST   

    if(move_uploaded_file($_FILES["imgBase64"]["tmp_name"], "/var/www/html/ecom1/site/test/final/".$fname))
    {
        echo '{"error":false, "message":null,"data":[{"msg": "Image has been saved successfully!", "fileName": "' . $fname . '"}]}';        
    }
    else
    {
        echo '{"error":true, "message":"File not uploaded"}';
    }

}

// another image code : 

//Show the image
echo '<img src="'.$_POST['img_val'].'" />';

//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('/var/www/html/ecom1/site/test/final/img.png', $unencodedData);

?>

这里是Full htmlphp code

0 个答案:

没有答案