Unable to upload image using axios in React with PHP - javascript

I am working on Reactjs and Php, Actually i am trying to upload image to server, Image is uploading but whenever i try to open image then showing "we dont support this file format", How can i fix this ?
I am sending formdata with multipart form data and in php (api) i am using base64 image for upload image to server
Is my apporach for sending image to axios (api) is correct or something wrong with php code
Here is my nextjs code
const handleSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
var imagefile = document.querySelector('#file');
formData.append("file", imagefile.files[0]);
const response = await axios({
method: "post",
url: "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
alert('respone is '+ response.data.msg);
}).catch(function (error) {
alert('respone is '+ error);
console.log("failed to get recommend playlist");
console.log('error is '+ error.msg);
});
}
And following is my Api code in Php side
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode(explode( ',', $files)[1]);
define('UPLOAD_DIR', 'uploads/');
$file_ext = strtolower( end(explode('.',$file_name)));
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.'.$file_ext;
file_put_contents($file, $image_base64);

The issues is from the PHP. You can just simplify it by using pathinfo() to get the extension and move_uploaded_file() to move the uploaded file to the server.
Try this
define('UPLOAD_DIR', 'uploads/');
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$file_name = UPLOAD_DIR . uniqid() . time() . '.' . $file_ext;
move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);

Related

File is corrupted after converting

I am using recorder.js library and want to send the recorded message to my gmail account using PHPMailer. I have done everything but the only problem that I am getting is that when I send the file as an attachment and download it from my mail, it is corrupted (or whatever) and my system says "The file is unplayable". Moreover, when I check my local uploads/ folder where I am writing all the files, they are unplayable too. I don't know what seems to be the problem and I am stuck on this since past two days. Thanks in advance.
My JS call to upload.php
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", blob, filename);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
and my upload.php
<?php
require "php-mailer-master/PHPMailerAutoload.php";
define('UPLOAD_DIR', 'uploads/');
$a = $_FILES['audio_data']['name'];
$a = str_replace('data:audio/wav;base64,', '', $a);
$a = str_replace(' ', '+', $a);
$data = base64_decode($a);
$file = UPLOAD_DIR . uniqid() . '.wav';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Please note that I have skipped the part of code which is actually sending mail because I believe that is irrelevant.

Uploading BLOB url to PHP server via ajax - Cordova

I am building a hybrid mobile app with cordova and is using the cordova camera plugin. I was able to get the blob:url for the image but hits a dead-end with uploading it to my back-end php server.
Background information:
I have two buttons that I have created to test the cordova camera api.
1 - Take Photo Btn -> Generates a blob url
2 - Upload Photo -> Suppose to upload the image captured based on the photo take to my server via ajax.
Based on my console, I am getting index:file not found and it generates a 0KB image file on my server. I am fairly new to ajax and blob so would appreciate any assistance rendered.
//JS CODE
uploadimgtoserver : function () {
//x is the blobimage url blob:http://localhost:8000/cb420014-a0b9-481a-b3ea-
6657f7e7c98e
var x = localStorage.getItem('data');
$.ajax({
url: 'URL',
type: 'POST',
data: {'file':x},
success: function (data) {
console.log(data);
},
});
}
};
//php code
$data = $_POST['file'];
$data = str_replace('data:image/jpeg;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = uniqid() . '.jpg';
$success = file_put_contents($file, $data);

Saving .toDataURL() on server using PHP Error 500

I have this function from a GitHub repo that outputs a drawn signature on canvas to a DataURL(). When I inspect it, it comes back as a string of encoded data(a .png).
The user clicks the save button and this happens:
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
saveSignature(signaturePad.toDataURL());
}
});
function saveSignature(dataURL) {
$.ajax({
type: "POST",
datatype: "json",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
signaturePad.clear();
}
Then it triggers a PHP script in the same folder, called script.php.
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I can't find out why it's causing a 500 server error.
The console isn't printing 'unable to save file', nor 'saved.'
You have error in script.php you are receving data in $img while write using $data so need to replace variable
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $img); //<---- change here
print $success ? $file : 'Unable to save the file.';
?>

Angular + PHP file upload (can't sent newly created properties)

I'm using ng-file-upload
.
It works perfectly, But I need to add some specific properties to object that I sent. Here controller method:
self.uploadFiles = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
files[i].upload_folder = 'upload'; //here i add first property
files[i].current_date = getCurrentDate(); //here second
var file = files[i];
console.log(files[i]);
Upload.upload({
url: 'app/views/antonovich/upload.php',
headers: {'Content-Type': undefined},
method: 'POST',
data: file,
file: file
}).progress(function(evt){
self.uploadProgress = parseInt(100.0 * evt.loaded / evt.total);
//console.log('progress: ' + self.uploadProgress + '% ' + evt.config.file.name);
}).success(function(data, status, headers, config){
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
$('.errors').html(data);
self.uploadReady = config.file.name + ' uploaded.';
});
}
}
}
In console log I see that properties, for example:
File {$$hashKey: "object:19", upload_folder: "upload", current_date: "2016-01-08"}
$$hashKey: "object:19"
current_date: "2016-01-08"
file: File
lastModified: 1448878298580
lastModifiedDate: Mon Nov 30 2015 13:11:38 GMT+0300 (Russia Standard Time)
name: "14488072165280.png"
size: 872713
type: "image/png"
upload_folder: "upload"
webkitRelativePath: ""
__proto__: File
PHP script uploads these files to folder and creates DB row, But 2 created properties are undefind, and return just this:
Response: Array
(
[name] => 14488072165280.png
[type] => image/png
[tmp_name] => C:\wamp\tmp\phpC39D.tmp
[error] => 0
[size] => 872713
)
here php script example:
<?php
if(isset($_FILES['file'])) {
print_r($_FILES['file']);
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$upload_folder = $_FILES['file']['upload_folder'];
$current_date = $_FILES['file']['current_date'];
print_r($upload_folder);
print_r($current_date);
$db = new PDO('mysql:host=localhost;dbname=antonovich', 'root', '');
$query = "INSERT INTO portfolio(url,date) VALUES('$file_name','$current_date')";
$stmt = $db->prepare($query);
$stmt->execute();
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
move_uploaded_file($file_tmp,"../../img/".$upload_folder."/".$file_name);
echo $file_name . " uploaded file: " . "images/" . $file_name;
}
else {
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>
For background, see PHP documentation on file uploads. The $_FILES superglobal only contains a fixed set of values about each uploaded file (name, type, tmp_name, error, and size), any other data from the POST request should be in the $_POST superglobal instead. Try changing your PHP script like so:
$upload_folder = $_POST['upload_folder'];
$current_date = $_POST['current_date'];
As a side note, I would be wary about allowing clients to specify the destination folder without robust validation. Attackers might be able to use relative paths to upload malicious code.

404 on POST but 200 on GET

I met a problem that when I make a POST request, the server responses with 404 error, while making GET request, it responses with 200.
Here are the methods that I have tried:
$.ajax({
type:"POST",
url: "script.php",
data:{
imgBase64: data
}
}).done(function(o) {
console.log('saved');
});
And:
var data = new FormData();
data.append("data" , dataURL);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', 'script.php', true );
xhr.send(data);
Further more I have tried to include:
header("HTTP/1.0 200 OK", true);
header('Access-Control-Allow-Origin: *');
in the php script. But none of them works.
Anyone has idea? Thanks!
EDIT:
Here is the php script. By the way, I am using nodejs...
<?php
// requires php5
header('Access-Control-Allow-Origin: *');
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I am new to nodejs and finally I found that I should write a function in server.js to process the get request.

Categories