Skip to content Skip to sidebar Skip to footer

Pass File From Javascript Upload To Php

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 api. So I was thin

Solution 1:

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

Solution 2:

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:

// xhrvar http = newXMLHttpRequest();
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 ...

Post a Comment for "Pass File From Javascript Upload To Php"