dpwdldgn43486 2016-02-05 02:33
浏览 62

使用Javascript和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>
  • 写回答

1条回答 默认 最新

  • dongzhu3548 2016-02-05 02:55
    关注

    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; 
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号