dongqixuan3112 2015-07-16 06:29
浏览 61

PHP使用jquery和PHP在用户请求上重命名或替换上传的文件

I am developing a PHP application in which I have to upload multiple files on the server, what I want is that when a user uploads multiple files the system should check if any of the files already exists, if yes then it should ask the user whether to rename the file or replace the older file,if user selects the rename option it should rename the file and if the user asks to replace the file it should do accordingly.

Untill Now I am using the following Code to upload the files:

<?php
if(isset($_FILES['files'])){
$errors= array();
     foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
    $file_name = $_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];  
if($file_size > 2097152){
    $errors[]='File size must be less than 2 MB';
}       
 //   $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="../reztrictedfolder/dir1/";
if(empty($errors)==true){
    if(is_dir($desired_dir)==false){
        mkdir("$desired_dir", 0700);        // Create directory if it does not exist
    }
    if(file_exists("$desired_dir/".$file_name)==false){
        move_uploaded_file($file_tmp,"../reztrictedfolder/dir1/".$file_name);
    }else{                                  //rename the file if another one exist

         //rename($file_tmp,$new_dir) ; 
        list($txt,$ext) = explode(".", $file_name);

        $actual_image_name = time().substr(str_replace(" ", "_", $txt),     5).".".$ext;
     $new_dir="../reztrictedfolder/dir1/".$actual_image_name."_copy";
        move_uploaded_file($file_tmp,$new_dir);              
    }
  //  mysql_query($query);          
}else{
       // print_r($errors);
}

But it only checks if the file already exists and rename it, but I want to let the user know that file already exists and if he wants to rename the file or replace the existing file..?

  • 写回答

1条回答 默认 最新

  • doukun8670 2015-07-16 07:28
    关注

    If you use AJAX so you sent from PHP response to JavaScript, which contains a list of file. I've use a function json_encode as parameters list of file. In javascript use JSON.parse()

    HTML Section

    <form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">
    
    <fieldset>
    <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
    <div>
        <label for="fileselect">Files to upload:</label>
        <input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
        <div id="filedrag">or drop files here</div>
    </div>
    
    <div id="submitbutton">
        <button type="submit">Upload Files</button>
    </div>
    
    </fieldset>
    
    </form>
    

    JavaScript

    function FileSelectHandler(e) {
        var files = e.target.files || e.dataTransfer.files;
    
        for (var i = 0, f; f = files[i]; i++) {
            UploadFile(f);
        }
    
    }
    
    function ResponseParse(data) {
         if (typeof data === "object") {
             for (var i = 0, lng = data.files.length; i < lng; i++) console.log(data.files[i]);
         }
    }
    
    function UploadFile(file) {
        var xhr = new XMLHttpRequest();
        // for example only jpeg file allowed
        if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
            xhr.open("POST", $id("upload").action, true);
            xhr.setRequestHeader("X_FILENAME", file.name);
            xhr.onreadystatechange = function() {//Call a function when the state changes.
                if(http.readyState == 4 && http.status == 200) {
                    // Response from server
                    var data = JSON.parse(http.responseText);
                    ResponseParse(data);
                }
            }
            xhr.send(file);
    
        }
    
    }
    

    PHP

    <?php
    $fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
    if ($fn) {
        file_put_contents(
            'uploads/' . $fn,
            file_get_contents('php://input')
        );
        exit;
    
    }
    else {
        $files = $_FILES['fileselect'];
        $uploaded['files'] = array();
    
        foreach ($files['error'] as $id => $err) {
            if ($err == UPLOAD_ERR_OK) {
                $fn = $files['name'][$id];
                $uploaded['files'][] = $files['name'][$id];
                move_uploaded_file(
                    $files['tmp_name'][$id],
                    'uploads/' . $fn
                );
            }
        }
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($uploaded);
    }
    

    This example working with XMLHttpRequest2. List of supported browser http://caniuse.com/#feat=xhr2. If you support old browser, you must old form-style upload or iframe upload idally by jquery, like this https://blueimp.github.io/jQuery-File-Upload/

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看