upload array of files with ajax - php

I have form that allow me to submit text + number of files. the form submitted with AJAX.
Because it's a number of files my upload function give me error:
Warning: move_uploaded_file(images/usersFiles/14367317720-101.JPG) [function.move-uploaded-file]: failed to open stream: No such file or
directory in C:\Program Files
(x86)\wamp\www\new-site\func\global.func.php on line 134
line 134 is:
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
files' var should be array (because I can load number of files).
How can I fix the error?
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<textarea class="form-control" name="post[text]"></textarea>
<input type='file' name='file[]' class='multi form-control' maxlength='1' accept='gif|jpg|png|bmp' id="files"/>
<a class="btn btn-primary" id="submit">submit</a>
</form>
JS:
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file[]', file_data);
var files_data = form_data;
var act = 'add';
form_data.append('act', act);
form_data.append('post[text]', $("#addCommentForm").find("textarea").val());
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
server:
function upload_files ($ownerID, $msg, $files, $type)
{
$dateLX = get_current_linuxTime();
///////// Upload files //////////////
if(!empty($files))
{
foreach($files['file']['name'] as $i => $fileName)
{
$fileSurffix = pathinfo ($_FILES['file']['name'][$i]);
$fileSurffix = $fileSurffix['extension'];
$files['file']['name'][$i] = str_replace(' ','',$files['file']['name'][$i]);
$files['file']['name'][$i] = $dateLX.$i."-".$ownerID.".".$fileSurffix;
$fileName = $files['file']['name'][$i];
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
{
$uploadFilesQuery = "INSERT INTO `files` (ownerID, name, type)
VALUES('$ownerID', '$fileName', '$type')";
$res = mysql_query($uploadFilesQuery);
if (!$res)
$msg['error']['uploadFile'] = "error <br />".mysql_error();
}
elseif ($files['file']['error'][$i] != 4)
$msg['error']['uploadFile'] = "ERROR ";
}
}
return ($msg);
}

USER_FILES must be an absolute path like
"C:\Program Files (x86)\wamp\www\new-site\images\usersFiles\"

Related

Form field input isn't received by JSON AJAX script

I am unable to catch the $productid from the form. Not sure what I'm doing wrong. Any ideas?
The selected files do upload, but not to the product folder specified, and nothing about the success is returned to index.php
It's strange but stackoverflow also mentions when trying to post "It looks like your post is mostly code; please add some more details", but I have no more info to add?
Thanks
index.php
<form method='post' action='' enctype="multipart/form-data">
<input type="hidden" id='productid' name="productid" value="<?=$productid?>">
<input type="file" id='files' name="files[]" multiple><br>
<input type="button" id='submitphotos' value='Upload'>
<!-- Preview -->
<div id='successupload'></div>
<div id='preview'></div>
<script>
$(document).ready(function(){
$('#submitphotos').click(function(){
var form_data = new FormData();
// Read selected files
var totalfiles = document.getElementById('files').files.length;
var productid= $("#productid").val();
for (var index = 0; index < totalfiles; index++) {
form_data.append("files[]", document.getElementById('files').files[index]);
}
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
for(var index = 0; index < response.length; index++) {
var src = response[index];
// Add img element in <div id='preview'>
$('#preview').append('<img src="'+src+'" width="400px;">');
}
$('#successupload').append('<h6>Successfully uploaded</h6>back');
files.style.display = "none";
submitphotos.style.display = "none";
}
});
});
});
ajaxfile.php
// Count total files
$countfiles = count($_FILES['files']['name']);
// Get product id
$productid = $_POST['productid'];
//Create request id folder if doesn't exist
if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/')) {
mkdir($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/', 0777, true);
}
// Upload directory
$upload_location = $_SERVER['DOCUMENT_ROOT']."/images/products/".$productid."/";
// To store uploaded files path
$files_arr = array();
// Loop all files
for($index = 0;$index < $countfiles;$index++){
if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
// File name
$filename = $_FILES['files']['name'][$index];
// Get extension
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Valid image extension
$valid_ext = array("png","jpeg","jpg","svg");
// Check extension
if(in_array($ext, $valid_ext)){
// File path
$path = $upload_location.$filename;
// Upload file
if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
$files_arr[] = $path;
}
}
}
}
echo json_encode($files_arr);
die;
</script>
You haven't passed the productid to the ajax call so just before ajax call add this:
form_data.append('productid', productid);
and your code should work fine.

move_uploaded_file doesn't move image to permanent folder || PHP

I am building a PHP application where a new user has to upload an avatar.
I managed to save the uploaded file path into my database,
but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'.
I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.
I have also tried copy() instead of move_uploaded_file with no luck.
HTML:
<div class="input-form">
<label for="avatar">Kies een profielfoto</label>
<input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
<img id="output" width="150" />
<input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>
PHP:
if(!empty($_POST)){
$fileSize = $_FILES["avatar"]["size"];
if($fileSize < 2000000){
$fileSizeOk = true;
}else{
throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
$imgSizeOk = false;
}
$img = $_FILES["avatar"]["name"];
if($imgSizeOk == true){
move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");
}
}
EDIT: was asked to share my JS code:
a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
let image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
Suggested solution with AJAX
$('#submit-btn').on('click', function() {
var file_data = $('#avatar-input').prop('files')[0];
var form_data = new FormData();
form_data.append('avatar', file_data);
alert(form_data);
$.ajax({
url: 'profielVervolledigen.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
}
});
});
with the following php code:
if(!empty($_POST)){
if ( 0 < $_FILES['avatar']['error'] ) {
echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
}
}
the alert gives [object FormData]
Thanks for any help

Saving images into database

I'm trying to save images in a mysql database. It saves binary code into the table, but its corrupt and i can't display it. Also the size of the database field is bigger than the original file. Is there anything wrong in my code or in the approach im having.
I know thats its not a good practice to store images in a database, but im not in the position to decide it.
<div class="box-body">
<h3>Bilder</h3>
<form id="image_form">
<input type="file" name="frame" id="file_name" />
<input type="submit" value="Save">
</form>
</div>
$('#image_form').on("submit",(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: './index.php?action=585',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function (a) {
//a.overrideMimeType('image/jpeg; charset=UTF-8');
},
success: function (data) {
console.log(data);
},
error: function () {
location.reload();
}
});
}));
Back-End
//Get the content of the image and then add slashes to it
$tmpName = $_FILES['frame']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
var_dump($data);
$imagetmp = $data;
AccountDAO::updateResImages($imagetmp, $imagetmp, $imagetmp, $_SESSION['customer']->id);
Database
public static function updateResImages($img1, $img2, $img3, $customerid){
$db = new MySQLDatabase();
$sql = "UPDATE customer SET online_res_bild1 = ?, online_res_bild2 = ?, online_res_bild3 = ? WHERE customer_id = ? ";
$rs = $db->executeQuery($sql, 'sssi', $img1, $img2, $img3, $customerid);
$db->close();
return 1;
}

Not able to upload image via jquery, ajax and PHP

I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.
I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.
I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:
HTML
<div id="loginButton2">
<div id="personalimg" >
<img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
</div>
</div>
<div id="loginBox2" style="display:none">
<div id="loginForm2" class="floatLeft" >
<fieldset>
<input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
<input id="file_submit" type="hidden" name="submit4" value="1" >
</fieldset>
</div>
</div>
JS
$('#file').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
var fd = new FormData();
var file = $("#file").prop("files")[0];
fd.append('profile_img', file);
fd.append('submit4', 1);
fd.append('filename', 1);
oFReader.onload = function (oFREvent) {
$.ajax({
url: "upload.php",
dataType: 'image',
cache: false,
contentType: false,
processData: false,
type: "POST",
data: fd,
success: function(data){
console.log(data);
},
error: function(){
console.log("image upload failed");
}
});
$('#loginForm2').toggle();
$('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
};
});
PHP
if(isset($_POST['submit4'])) {
$check_sql = "select profile_pic from profile where user_id=$user_id";
$check_rs = mysql_query($check_sql);
$check_num = mysql_num_rows($check_rs);
if($check_num==0) {
$sql = "insert into profile(user_id) values($user_id)";
$rs = mysql_query($sql);
}
$fName = $_FILES["profile_img"]["name"] ;
$data = explode(".", $fName);
$fileName = $user_id.'.'.$data[1];
if($fName!='')$user->update('profile_pic',$fileName);
$fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
//image store path
$pathAndName = "photos/seller_photos/".$fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
if(move_uploaded_file) {
$response['status'] = '1';
header('Location: edit_profile_new.php');
} else {
$response['status'] = '0';
}
return $response;
}
But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.
Can someone please help me out?
ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.

PHP file upload not working. Getting error:

To start things off, I've looked at a few similar problems on here but still can't resolve my issue here.
HTML:
<input type="file" name="filename" multiple="multiple" data-classIcon="icon-plus" data-buttonText="Upload Your File">
PHP:
$name = $_FILES['filename'];
$temp_name = $_FILES['filename']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'uploaded';
}
}
} else {
echo 'error: not uploaded';
}
JS:
$('#cc-submit').on('click', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "balanced/example.php",
data: $('#creditcardpost').serialize(),
success: function(data)
{
alert(data);
}
});
});
Error:
Undefined index: filename in /public_html/script.php on line xx (the two lines that collect the $_FILES variables.
"error: not uploaded"
You must use:
$name = $_FILES['filename']['name'];
I used print_r on $_FILES and found my files were coming through as "file-0". I'm not doing multi file uploads, so this works for me. And here is the solution. PHP:
$name = $_FILES['file-0']['name'];
$temp_name = $_FILES['file-0']['tmp_name'];
$location = '../uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
}
print_r($name);
And the JS that sends it needed to be worked a bit:
var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: 'balanced/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
$('#creditcardpost').append('<input type="hidden" value="' + data + '" name="filename" />');
}
});
I've got it working. Thanks for helping out guys.

Categories