I want to uploade a file and send additional data (an array) to the php script.
Here is the HTML and the Javascript Code:
<input type="file" name="fileinput" id="fileinput">
<button class="btn btn-primary" id="btnupload">upload</button>
<script>
$('#btnupload').click(function(){
var formData = new FormData();
formData.append("MacsToChangeImage", selectedMACs.toString()); //selectedMACs is the array which i want to send
formData.append("userfile", $('#fileinput').files[0]);
$.ajax({
url: "ChangeImagesFunction.php",
type:'POST',
data: formData,
processData: false,
cententType: false,
success: function(data)
{
alert('success' + data);
},
error:function(response){
alert(JSON.stringify(response));
}
});
});
</script>
And here ist the PHP Code:
if(!empty($_FILES)) {
$target_dir = "img/epd_uploads/";
$temporaryFile = $_FILES['userfile']['tmp_name'];
$targetFile = $target_dir . $_FILES['userfile']['name'];
if(!move_uploaded_file($temporaryFile,$targetFile)) {
echo "Error occurred while uploading the file to server!";
}else{
if (isset($_POST['MacsToChangeImage'])){
//Name of the Uploaded File
$ChangeImageToPHP = $_FILES['userfile']['name'];
//Get the Array
$MacsToChangeImageStr = $_POST['MacsToChangeImage'];
$MacsToChangeImagePHP = explode(",",$MacsToChangeImageStr);
}
}
}
I think the HTML and Javascript part is fine so far. But i am uncertain how to handle the PHP part. What am i doing worng/missing?
Are there other ways to achieve what im plannig to do?
Thank you in advance
Related
I have a simple form so you can upload images. I store the uploaded images' properties in a array but I want to post this array to a PHP file using ajax. If I try to get the uploaded image: $_FILES['image1'], it returns an empty array. Any idea what I am doing wrong?
PS: It is important to store the images' properties in a array and pass it to a FormData.
var foo = []; var input = document.getElementById('input');
document.getElementById('add').addEventListener('click', () => {
foo.push(input.files[0]);
});
document.getElementById('check').addEventListener('click', () => {
console.log(foo);
});
document.getElementById('upload').addEventListener('click', () => {
var fd = new FormData();
for (let i = 0; i < foo.length; i++) {
fd.append('image'+i, foo[i]);
}
$.ajax({
enctype: "multipart/form-data",
type: "POST",
url: "path/to/php.file",
data: fd,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) { console.log(data); },
error: function (err) { console.log(err); }
});
});
<button id="add">ADD</button>
<button id="check">CHECK</button>
<button id="upload">UPLOAD</button>
<br><br>
<input type="file" id="input" placeholder="UPLOAD IMAGE">
And the PHP file:
<?php
$arr = array();
array_push($arr, $_FILES);
die(json_encode($arr));
?>
Or you need to check php.ini and check if the size of all the images you add exceeds "upload_max_filesize"
I executed the code with two files. It seems that you can print the files successfully with the following code (PHP file)
print_r($_FILES['image0']);
print_r($_FILES['image1']);
I used jquery 3.5.1, for the ajax call.
I hope it helps.
in PHP page with multiple form tag to register user information.
using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.
my html code:
<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>
Javascript Code:
let data1 = document.getElementById('data1').value,
data2 = document.getElementById('data1').value,
data3 = document.getElementById('data1').value,
upimage = document.getElementById('upimage').value;
$.ajax({
url:"././newregister.php",
method:"POST",
data:{action:'newregister', data1:data1, data2:data2,
data3:data3, upimage:upimage},
success:function(data){
alert(data);
}
});
newregister php code:
$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
echo "Sucsess";
}
else
{
echo "Error" . $_FILES["file"]["error"] ;
}
ERR: Undefined index: file in .... on line ....
Given by POST method uploads
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.
As ferikeem already said. Wrap your data in a FormData Object and send it that way.
See: https://stackoverflow.com/a/5976031/10887013
JavaScript
let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);
$.ajax({
url: "././newregister.php",
method: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert(data);
}
});
$_FILES["file"], here is your problem.
In $_FILES array key "file" doesn't exists. As I see you need to change $_FILES["file"] with $_FILES["upimage"].
Currently, I have the following code that will allow me to upload only one image to the server at the time.
But what I want to do is to upload multiple images. I don't mind if it will send multiple request to the server, but I want to replace the following code, so that I can drag and drop or select multiple images at a time and send it with ajax. How will I be able to achieve this ?
I tried to use some libraries that I found on the web such as dropzone.js, but it seems like it doesnt do the trick. Some simple samples or tips would be great ! I would love to hear from you !
HTML code
<div>
<input type="file" name="mydata[]"/>
<span class="btn" onclick="imgToMyServer('$(this));">Fly Me to the Server ! </span>
</div>
JS side
<script>
function imgToMyServer(ob) {
var form = $('<form />');
var files = ob.prev('input[type="file"]');
var simplefile = files.prop('files')[0];
var Myname = simplefile.name;
var input = $('<input name="mydata[][my_path]" value="path/' + Myname+ '"/>');
switch (simplefile.type) {
case "image/jpeg":
break;
case "image/png":
break;
case "image/gif":
break;
default:');
return false;
break;
}
files.after(files.clone());
files.appendTo(form);
input.appendTo(form);
datas = new FormData(form[0]);
$.ajax({
type: 'post',
processData: false,
contentType: false,
data: datas,
url: "https//www.sample.com/uploads_my_images",
async: true,
success: function (res) {
//Just happy
}
});
}
</script>
What you need its quite simple first you need to add the multiple attribute on the file input type so that it allows you to select multiple files.
Then you need to check the number of images that are selected, then loop through the array of images that are selected then append the images dynamically to the form data :
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div>
<input type="file" name="mydata[]" id ="multiFiles" multiple="multiple">
<button id="upload" class="btn">Fly Me to the Server !</button>
<div id="msg"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#upload').on('click', function (e) {
e.preventDefault();
var form_data = new FormData(); //create form data object
var num_files = document.getElementById('multiFiles').files.length;
for (var x = 0; x < num_files; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]); //append the files to the form data object
}
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, could be json,html
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
server :
<?php
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
}
}
}
} else {
echo 'Please choose at least one file';
}
NB: I did not do any validation of the file uploaded, I just uploaded
straight, you need to validate in both the client and the server side.
I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
i am trying file uploading to php my server.file and data uploading through multi part /form-data ,the file and data received on php server but in my php server return json response .please help me how to read json response in my webpage and if its success(code=0) means it redirect another page .the php sever is common for both android and web pages .json response look like {"code":0,"message":"success"}
<div style="height:0px;overflow:hidden">
<form id="myForm" action="http://192.168.2.4/digiid/api/addid"
method="post" enctype="multipart/form-data" runat="server">
<input type="file" name="file" id="file" onchange="showMyImage(this)" />
<input type="hidden" name="userid" value="<?php echo $_SESSION["userid"]?>">
<input type="hidden" id="inputfilename" name="filename" value="here">
</form>
</div>
<a class="button1" id="browseButton" onclick="" style="width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Select ID</font></a>
<br/>
<div>
<img src='images/capture_picture_size.png' id='imgscreen' width='200' height='200'>
<br/>
<p id="filename" style="color: #ffffff; font-size: 20px" >
Title of the ID<br/></p>
<a class="button1"onclick="myFunction()" style= " width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Save ID</font></a></form>
</div>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
<script>
browseButton.onclick=function chooseFile() {
document.getElementById("file").click();
};
function showMyImage(fileInput) {
var files = fileInput.files;
var file = files[0];
var imageType = /image.*/;
var img=document.getElementById("imgscreen");
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
//x=e.target.result
img.src = e.target.result;
var extfilename=file.name;
document.getElementById("filename").innerHTML=extfilename.slice(0,-5) ;
document.getElementById("inputfilename").value=extfilename.slice(0,-5);
};
})(img);
reader.readAsDataURL(file);
}</script>
I think it should work for you. Using AJAX, as I do
//Your php code
$arrToJSON = array(
"dataPHPtoJs"=>"yourData",
"asYouWant"=>"<div class=\".class1\">soemting</div>"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_Login",
dataJsToPHP: $("#txt_EmailLogin").val()
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "yourServer.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
dataPHPtoJsJS=dataset[index].dataPHPtoJs;
asManyasYouWantJS=dataset[index].asYouWant;
}
//JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
if(dataPHPtoJsJS){
$( "#idYourHtmlElement" ).removeClass( "class1" )
$( "#idYourHtmlElement" ).addClass( "class2" )
}
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
You should probably use an AJAX call. Here's a solution using jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#browseButton").click(function(){
var url = "";
var formdata = $("#myForm").serialize();
$.ajax({
url: url,
type: 'POST',
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(response){
if(response.status == "success"){
// Success
} else {
// Failure
}
},
error: function(response){
// Error
}
});
});
});
</script>
In order to redirect the user, you can use: window.location.href = " ... your_url ...";
Here's an explanation on how to use jQuery AJAX and multi-part data:
Sending multipart/formdata with jQuery.ajax
try json_decode.
$data = ({"code":0, "message":"success"});
$array = json_decode($data, true);
by passing 2nd parameter to true you will get response in array instead of object.
the array will be then populated as follow:
array (size=2)
'code' => int 0
'message' => string 'success' (length=7)
Your JSON response would be a kind of associative array in php.
Encode your array data into JSON using "json_encode" and return values as you want .
$arr = array('status' => $status, 'status2' => $status2, );
echo json_encode($arr);
NOTE: If you are using ajax to call php file then do not use any php echo/print in that file and not even HTML. ECHO only "json_encode();" Nothing else.
To sum it up:
Upload your data to server using AJAX with native JS (>=IE10) or jQuery
Catch (xhr.responseText in native JS) and parse the response
Redirect with window.location.href="success.php"