简体   繁体   中英

Upload resized image, and name for that image using Javascript and php.

I have been researching this problem for 2 weeks now. I have found many solutions for resizing and upload, but none that combine both requirements. I have found a nice solution for resizing an image and uploading it to php. However the uploaded file is given a unique ID, name. I would like to give the image file my own ID, name, which I would like to get from a Form with an Input field. I only wish to load up one resized image at a time.

Below is the code that is working as far as uploading the resized image.

<?php
if ($_POST ) {
    define('UPLOAD_DIR', 'photo_test/');
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);  // remove Header for image
    $img = str_replace(' ', '+', $img);                       // insert + sign for space
    $data = base64_decode($img);                              // restore data to original format, binary
    $file = UPLOAD_DIR . uniqid() . '.jpg';                   // set file location & name 
    $success = file_put_contents($file, $data);               // Save the image file
    print $success ? $file : 'Unable to save the file.';
 }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<div class="row">
      <label for="fileToUpload">Select Files to Upload</label><br />
      <input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
      <output id="filesInfo"></output>
</div>
<form name="Upload_Image" id="Upload_Image" enctype="multipart/form-data" method="post" action="uploadResized.php">
<div class="row2">
   Enter name for output file:&nbsp; <input  id="Image_Name" name="Image_Name" />&nbsp;&nbsp;&nbsp;
  <input name ="Load_Data" type="submit" value="Upload Data" />
</div>
</form>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('filesToUpload').onchange = function(){
        var files = document.getElementById('filesToUpload').files;
        for(var i = 0; i < files.length; i++) {
            resizeAndUpload(files[i]);
        }
    };
} else {
    alert('The File APIs are not fully supported in this browser.');
}
function resizeAndUpload(file) {
var reader = new FileReader();
    reader.onloadend = function() {
    var tempImg = new Image();
    tempImg.src = reader.result;
    tempImg.onload = function() {
        var MAX_WIDTH = 1200;
        var MAX_HEIGHT = 1000;
        var tempW = tempImg.width;
        var tempH = tempImg.height;
        if (tempW > tempH) {
            if (tempW > MAX_WIDTH) {
               tempH *= MAX_WIDTH / tempW;
               tempW = MAX_WIDTH;
            }
        } else {
            if (tempH > MAX_HEIGHT) {
               tempW *= MAX_HEIGHT / tempH;
               tempH = MAX_HEIGHT;
               }
        }
        var canvas = document.createElement('canvas');
        canvas.width = tempW;
        canvas.height = tempH;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, tempW, tempH);
        var dataURL = canvas.toDataURL("image/jpeg");
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(ev){
            document.getElementById('filesInfo').innerHTML = 'Done!';
        };
        xhr.open('POST', 'uploadResized.php', true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var data =  'image=' + dataURL; 
        xhr.send(data); 
      }
   }
   reader.readAsDataURL(file);
}
</script>
</body>
</html>

you can simple edit the code, and get your purpose:

<?php
    if ($_POST ) {
        define('UPLOAD_DIR', 'photo_test/');
        $img = $_POST['image'];
        $img = str_replace('data:image/jpeg;base64,', '', $img);  // remove Header for image
        $img = str_replace(' ', '+', $img);                       // insert + sign for space
        $data = base64_decode($img);                              // restore data to original format, binary

        // get image name.
        $imgName = $_POST['imgName'];
        // uniqid() can simple replace with an image name
        $file = UPLOAD_DIR . imgName . 'some id' . '.jpg';                   // set file location & name 
        $success = file_put_contents($file, $data);               // Save the image file
        print $success ? $file : 'Unable to save the file.';
    }
?>
...
if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('filesToUpload').onchange = function(){
        var files = document.getElementById('filesToUpload').files;

        // get image name.
        var ImageName = document.getElementById('Image_Name');
        for(var i = 0; i < files.length; i++) {
            resizeAndUpload(ImageName, files[i]);
...
// pass the ImageName to function
function resizeAndUpload(ImageName, file) {
...
        // send it to php too
        var data =  'ImageName='+ImageName+'&image=' + dataURL; 
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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