How to send javascript variable to PHP server as $ _FILE

We have PHP code on the server that receives the files in $ _FILE and then saves them based on user / security considerations.

On the client, we can send the file to the server as is, or we would like to process the file locally (in memory in js in the browser), and then deliver the file to the server. We can send the processed file to the server using JSON, however, there are problems with this.

We would prefer to send the contents of the client javascript variable to the server, which will be received in $ _FILE. (We cannot assume that the client will be able to save the file locally.) Do we need to somehow imitate the FORM view?

How to send a javascript variable to be retrieved as PHP $ _FILE?

Thank!

UPDATE Obviously, Blob is the right direction, but we notice that the size of Blob comes out 50% larger than the file that comes to it. The file in $ _FILE is also 50% larger. We tried to override the file type when creating Blob, based on other messages, such as BlobBuilder destroying binary data , but it did not record a 50 percent increase in size. We set the Blob file type based on the type of drag and drop file we get. For example, we upload a PDF file of 900K. The type was something like "application / pdf". The resulting blob was like 1400K. Also tried with PNG.

+4
source share
4 answers

Blob XHR2 (FormData), . , data, , ,

// Set the file media type appropriately
var blob = new Blob([ data ], { type: "image/png" });

var formData = new FormData();
formData.append("theFile", blob, "filename.png");

var xhr = new XMLHttpRequest();
xhr.open("POST", "/destination");
xhr.send(formData);
xhr.onload = function() {
    // ...
};

UPDATE: XHR2, AJAX, a .

, multipart/form-data . , , IE6-9.

+3

, , PHP $_ FILE, $_ SERVER [ 'HTTP_X_FILENAME']. JS-.

function UploadFile(file) {
    var xhr = new XMLHttpRequest();
    if (xhr.upload && file.size <= $id("MAX_FILE_SIZE").value)
    {
        // start upload
        xhr.open("POST", $id("upload").action, true);
        xhr.setRequestHeader("X-FILENAME", file.name);
        xhr.onload = function(e) {
            if (this.status == 200) {
                ... Some processing script for returning messages
            }
        };
        xhr.send(file);
    }
}

PHP :

$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
    $file = "desired location/" . $fn;
    file_put_contents($file,file_get_contents('php://input'));
}

JS UploadFile .

+1

MaxArt

Php:

$file = $_POST['theFile'];//sent from javascript
$filePath = "/your_destination_directory/filename.ext";

if(file_put_contents($filePath,$file))
{
    //OK
}else{
    //ERROR
}
0
0

Source: https://habr.com/ru/post/1583964/


All Articles