Pass file from Javascript upload to PHP

前端 未结 2 786
醉梦人生
醉梦人生 2021-01-12 17:10

I\'m working on a script to let the user upload a file and sees a upload status and the file is then saved on the server.

The problem is that I cannot use the php ap

相关标签:
2条回答
  • 2021-01-12 17:49

    Make an AJAX request to a PHP file, send the uploaded file properties like name, etc. and let it open that, move that, rename that or whatever needed. It should works, huh?

    did I understood your question correctly?

    Sample Code:

    In Javascript:

    // xhr
    var http = new XMLHttpRequest();
    var url = "file_handler.php";
    var file_data = "name=mypic.jpg&size=123&othe=etc";
    http.open("POST", url, true);
    
    // headers
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", file_data.length);
    http.setRequestHeader("Connection", "close");
    
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    
    http.send(file_data);
    

    In file_handler.php:

    // file data
    $file_data = $_POST['file_data'];
    
    // working on the file
    $temp_dir = 'usr/upload/';
    $new_dir = 'usr/photos/';
    
    // new unique name
    $new_name = time() . '_' . $file_data['name'];
    
    // copy?
    if (copy($temp_dir . $file_data['name'], $new_dir . $new_name)) {
        unlink($temp_dir . $file_data['name']);
    }
    
    // rename?
    rename($temp_dir . $file_data['name'], $temp_dir . $new_name);
    
    // delete old file?
    unlink($temp_dir . $file_data['name']);
    
    // do whatever else needed here ...
    // echo some JSON data to interact with your client-side JS code, maybe ...
    
    0 讨论(0)
  • 2021-01-12 17:56

    I have a Gist on this. It uses xhr.send(FormData) and shows minimal code to handle the file in PHP.

    0 讨论(0)
提交回复
热议问题