Rename a file before uploading using plupload.Uploader code and remove file from queue not working

70 views Asked by At

I have two problems.
First of all the remove a file from queue is not working well. When I use remove link of the chosen file from queue, the link refresh the whole page. For example when I chose two files and I want to remove one of them with the remove link, with refreshing the page I lose both file in the queue. Do you have any suggestion what do I have to do differently?

Second problem:
I have an index with Java code from plupload.Uploader and a 2b-chunk.php as an upload file witch that code aloud me to upload large files and it works perfect.
But, I need to have the option rename the selected file before uploading it. So, I wrote an input code with ol to give the name as I wish there before I use the send button but I do not know what is the method sending it to 2b-chunk.php code for caching the new file name implanting to the code. Do you think my though is correct for my goal and what do I miss? If my code is correct what code do I have to change in my 2b-chunk.php to keep the chunk option with the new name of my file?

My plupload index code:

<title>Plupload - Custom example</title>
<link rel="stylesheet" href="css/x-dummy.css">
<!-- production -->
<script type="text/javascript" src="js/plupload.full.min.js"></script>



<!-- debug 
<script type="text/javascript" src="../js/moxie.js"></script>
<script type="text/javascript" src="../js/plupload.dev.js"></script>
-->
<style type="text/css">
#info_div_center {
    width:250px;
    height:auto;
    text-align: center;
    margin-top: -12px;
    }
ol.phpfmg_form{
    list-style-type:none;
    padding:2px 2px 2px 2px;
    font-family: 'Glyphicons Halflings', "Times New Roman", "serif";
    font-size: 12px;
    position: static;
    resize: vertical;
    width: 50%;
}
ol.phpfmg_form input{
    border: 1px solid #CCC;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 8px;
    padding:3px 3px 3px 3px;
    font-size: 12px;
    
}
.phpfmg_form input:hover {
    background:#E8E8E8;
}
input:focus::placeholder {
  color: transparent;
}
</style>

</head>
<body style="font: 13px Verdana; background: #eee; color: #333">

<h1>Custom example</h1>

<p>Shows you how to use the core plupload API.</p>

<div id="filelist">Your browser doesn't have HTML5 support.</div>
<br />
<form id="container" encType="multipart/form-data">
    <button id="pickfiles" href="javascript:;" multiple="false" />Select files</button>
    <button id="uploadfiles" href="javascript:;" type="submit">Upload</button>
</form>

<br />
<pre id="console"></pre>


<script type="text/javascript">
// Custom example logic

var uploader = new plupload.Uploader({
  runtimes: 'html5,flash,silverlight,html4',
  browse_button: 'pickfiles', // you can pass an id...
  container: document.getElementById('container'), // ... or DOM Element itself
  //max_retries: 1,
  //multipart: false,
  chunk_size: '1mb',
  //multiple_queues: false,
  //unique_names: true,
  url: "2b-chunk.php",

  filters: {
    max_file_size: '1000mb',
    mime_types: [
      { title: "Image files", extensions: "jpg,jpeg,gif,png" },
      { title: "Zip files", extensions: "zip" },
      { title: "Movie files", extensions: "mov,mp4" },
      { title: "Audio files", extensions: "mp3,wav" },
      { title: "Documents files", extensions: "pdf,doc,docx" }
    ]
  },
    flash_swf_url: 'js/Moxie.swf',    // Flash settings
    silverlight_xap_url: 'js/Moxie.xap',    // Silverlight settings

  init: {

    PostInit: function() {
            document.getElementById('filelist').innerHTML = '';
            document.getElementById('uploadfiles').onclick = function() {
                if (uploader.files.length < 1) {
                            document.getElementById('console').innerHTML = '<p style="color:#EA4335;">Please select a file to upload.</p>';
                    setTimeout(function () {
                    window.location.reload();
                    }, 2000)
                    return false;
                        }else{
                uploader.start();
                return false;
                }
            };
        },
      
      
      FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
                document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b> '+'<a href="" class="remove btn error">Remove</a>'+'<ol class="phpfmg_form"><input type="text" name="newfilename" placeholder="Type the new filename and press Upload"></ol>'+'</div>';
                
            });
        },
BeforeUpload: function(up, file) {
    uploader.settings.multipart_params = { 'renamedFileName': 'yourRenamedFileName' };
});
      
      
    UploadProgress: function(up, file) {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span style="color:red">' + file.percent + "%</span>";
        },

     FileUploaded: function(up, file, result) {
                    var responseData = result.response.replace('"{', '{').replace('}"', '}');
                    var objResponse = JSON.parse(responseData);
                    document.getElementById('console').innerHTML = '<p style="color:#198754;">' + objResponse.result.message + '</p>';
                },
      UploadComplete(up, file) {
      setTimeout(() => {
        window.location.reload();
      }, 3000);
    },
    
    Error: function(up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
            setTimeout(function () {
                    window.location.reload();
                    }, 2000)
                    return false;
        }
  },
});
uploader.init();
</script>
</body>

My 2b-chunk.php code

<?php 

// Settings 
$targetDir = 'uploads'; 
$cleanupTargetDir = true; // Remove old files 
$maxFileAge = 5 * 3600; // Temp file age in seconds 
 
// Create target dir 
if (!file_exists($targetDir)) { 
    @mkdir($targetDir); 
} 
 
// Get a file name 
if (isset($_REQUEST["name"])) { 
    $fileName = $_REQUEST["name"]; 
} elseif (!empty($_FILES)) { 
    $fileName = $_FILES["file"]["name"]; 
} else { 
    $fileName = uniqid("file_"); 
}
 
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled 
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; 
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; 
 
 
// Remove old temp files     
if ($cleanupTargetDir) { 
    if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); 
    } 
 
    while (($file = readdir($dir)) !== false) { 
        $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; 
 
        // If temp file is current file proceed to the next 
        if ($tmpfilePath == "{$filePath}.part") { 
            continue; 
        } 
 
        // Remove temp file if it is older than the max age and is not the current file 
        if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { 
            @unlink($tmpfilePath); 
        } 
    } 
    closedir($dir); 
}     
 
 
// Open temp file 
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) { 
    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); 
} 
 
if (!empty($_FILES)) { 
    if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); 
    } 
 
    // Read binary input stream and append it to temp file 
    if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); 
    } 
} else {     
    if (!$in = @fopen("php://input", "rb")) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); 
    } 
} 
 
while ($buff = fread($in, 4096)) { 
    fwrite($out, $buff); 
} 
 
@fclose($out); 
@fclose($in); 
 
// Check if file has been uploaded 
if (!$chunks || $chunk == $chunks - 1) { 
    // Strip the temp .part suffix off  
    rename("{$filePath}.part", $filePath);
}

echo('{"jsonrpc" : "2.0", "result" : {"status": 200, "message": "The file has been uploaded successfully!"}, "id" : "id"}');
?>

I need to have the option renaming my chosen file before uploading and need the option removing a file from queue before uploading.
Thanks in advance for your help

0

There are 0 answers