Sending a png file via AJAX for PHP. var_dump in PHP shows the following:

string (1462575) "------ WebKitFormBoundaryh7lE1zEduW95eI64 Content-Disposition: form-data; name =" file "; filename =" _ keys_inunity.png "Content-Type: image / png PNG IHDR D ....

When I try to view a saved image, I get an error that the file is damaged.
How to save via PHP file received via AJAX?

  <form> <input type="file" id="file" name="file"> <input type="submit"> </form> <script type="text/javascript"> $('form').submit(function (e) { var data; data = new FormData(); data.append('file', $('#file')[0].files[0]); $.ajax({ url: 'http://abc-site.com/script.php', data: data, processData: false, type: 'POST', contentType: 'multipart/form-data', beforeSend: function (x) { if (x && x.overrideMimeType) { x.overrideMimeType("multipart/form-data"); } }, mimeType: 'multipart/form-data', success: function (data) { alert(data); } }); e.preventDefault(); }); </script> php $content = file_get_contents("php://input"); $name = explode('filename="', $content)[1]; $name = explode('"', $name)[0]; var_dump($content); file_put_contents($name, $content); 
  • Naschel working code, but if anyone knows why the previous one did not work - I will be grateful for the answer. - J. Doe

1 answer 1

 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <form> <input type="file" id="file" name="file"> <input type="submit"> </form> <div id="res"></div> <script type="text/javascript"> $('form').submit(function (e) { var data; data = new FormData(); data.append('file', $('#file')[0].files[0]); $.ajax({ url: 'http://abc-site.com/script.php', data: data, dataType: 'text', cache: false, contentType: false, processData: false, type: 'post', success: function (data) { alert(data); //$('#res').append(data); } }); e.preventDefault(); }); </script> <?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], $_FILES['file']['name']); }