I'm using plupload to upload images in a form. When I press submit, the uploader.php does it job by uploading the images and processing the other form data using the multipart_params og pluploader.
However, I want to submit the form as well when no image is selected. When I submit with no image selected now, uploader.php simply doesn't run.
Is there a way to run uploader.php in all cases, even with no files selected?
Thanks.
This is the simplified code I'm working on:
<textarea id="textarea_input"></textarea>
<label id="browse" href="javascript:;">
<i class="fa fa-camera"></i> Add image
<span id="filelist"></span>
</label>
<a id="start-upload" href="javascript:;"">Add</a>
<span id="console"></span>
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'uploader.php',
multi_selection: false,
resize: {
width: 1500,
height: 1500,
quality: 30
},
filters: {
mime_types : [
{ title : "Image files", extensions : "jpg,gif,png,jpeg" }
],
max_file_size: "10mb",
prevent_duplicates: true
},
multipart_params : {
"textarea_input" : "value1" //predefine textarea_input here, uploader right before uploader.start()
}
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
while (up.files.length > 1) { //custom: limit to 1 file upload.
up.removeFile(up.files[0]);
document.getElementById('filelist').innerHTML = '';
}
var html = '';
plupload.each(files, function(file) {
html += '<br /><span id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></span>';
});
document.getElementById('filelist').innerHTML += html;
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
});
uploader.bind('UploadComplete', function(up, files) {
window.location = "mobilelogbook.php?saved=2";
});
document.getElementById('start-upload').onclick = function() {
uploader.settings.multipart_params["textarea_input"] = document.getElementById("textarea_input").value;
uploader.start();
};
</script>
And the uploader.php:
<?php
if (empty($_FILES) || $_FILES["file"]["error"]) {
$fileName = '';
} else {
$fileName = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "images/logbook/$fileName");
}
if (isset($_POST['textarea_input'])) {
$log = $_POST['textarea_input'];
} else {
$log = '';
}
// SQL GOES HERE: ADDS THE TEXTAREA_INPUT AND FILENAME TO A TABLE.
die('{"OK": 1}');
?>
Related
I'm not a php programmer. Someone ask me help for a web server with problem. I fix everything and update PHP 5.4 to 5.6. Everything work fine on his php program, except file upload.
Message: getimagesize(var/www/myserver/admin/uploads/temp/test.jpg): failed to open stream: No such file or directory
error on this line: $img_info = getimagesize("uploads/temp/$filename");
if($_POST['fileselect'][0] != "")
$filename=$_POST['fileselect'][0];
else
$filename=$_POST['dragfile'];
if(strlen($filename) > 3){
$finalname=time(); //Set a unique filename by the UNIX time
//Convert to jpg if tiff
$img_info = getimagesize("uploads/temp/$filename");
if($img_info['mime'] == "image/tiff"){
$clearname=explode(".", "$filename")[0];
system("convert uploads/temp/\"$filename\"[0] uploads/temp/$clearname.jpg");
unlink("uploads/temp/$filename");
$filename=$clearname.".jpg";
}
The problem probably come from a new code formulation in php5.6, any idea how to fix that ?
UPDATE 2: FILE UPLOAD section...
part of form.php
<form method="post" class="form-horizontal">
<input type="hidden" id="to_upload" name="to_upload" value="/upload.php">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000000" />
<input type="hidden" id="id_produit" name="id_produit" value="<?php echo $this->mdl_inventory->form_value('idproduit'); ?>" />
<div class="control-group">
<label class="control-label">Nouveau (jpeg): </label>
<div class="controls">
<input type="file" id="fileselect" name="fileselect[]">
</div>
</div>
Does the name fileselect[] can be the problem ? How can i check if the script go in "upload.php" ?
part of upload.php
/* read the source image */
$source_image = imagecreatefromjpeg("$src");
$width = imagesx($source_image);
$height = imagesy($source_image);
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/temp/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}else {
// form submit
$files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
ajax script filedrag.js (upload)
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/tiff" ) && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("to_upload").value + "?idproduit=" + $id("id_produit").value, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
$('#dragfile').attr('value', file.name);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
//submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The syntax for the code mentioned is correct for 5.6, no issues with that.
I don't see permissions as the issue as well, otherwise you'd have gotten a 'Permission denied' error.
So, most likely, it looks like, the file that you are looking for does not exist in the folder.
the error was here:
xhr.setRequestHeader("X_FILENAME", file.name);
X-filename... i think it's APACHE UPDATE problem.
Thanks for help.
I'm trying to make a script to upload files to my server.
What's really bothering me is that the success call is executed though the file is not uploaded.
HTML
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<label>Castellà</label><input name="mapa_es" id="mapa_es" type="file" />
<div id="progressbox_es" style="display:none;">
<div id="progressbar_es">
<div id="statustxt_es">0%
</div>
</div>
</div>
</form>
JS
$(document).ready(function() {
$('#mapa_es').change(function() {
var formData = (this.files[0]);
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
console.log(percentComplete + '%');
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%')
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%');
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
console.log(percentComplete + '%');
}
}, false);
return xhr;
},
url: 'processupload.php',
type: 'POST',
data: formData,
async: true,
beforeSend: function() {
},
success: function(msg) {
console.log(msg);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
and the PHP code in processupload.php
<?php
if (isset($_FILES["mapa_es"]) && $_FILES["mapa_es"]["error"] == UPLOAD_ERR_OK) {
$UploadDirectory = 'mapes/';
if ($_FILES["mapa_es"]["size"] > 5242880) {
echo "File size is too big!";
}
$File_Name = strtolower($_FILES['mapa_es']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.'));
$Random_Number = rand(0, 9999999999);
$NewFileName = $Random_Number . $File_Ext;
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded.';
} else {
echo 'error uploading File!';
}
} else {
echo 'Something wrong with upload!';
}
?>
I will appreciate any help you could give me. Thanks.
EDIT: I followed gtryonp suggestions and I got into more problems.
When I try to var_dump($_FILES) all I get is an empty string.
I also tried to submit the form using $().submit instead on $().change and it worked, I think it may be because of "enctype="multipart/form-data" on the form tag.
Is there any way to achieve it without having to submit the whole form?
Your processupload.php is ending with a die(message) and will be take as a normal program end, so the success event will be fired and the console.log('FILE UPLOADED') will be your response always, even in error cases. Change all your die(message) with echo message, something like:
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded to '.$UploadDirectory . $NewFileName;
} else {
echo 'error uploading File!';
}
...
and change the success function for something that echoes the possible answers to your screen. Something like:
success: function(msg) {
console.log(msg);
},
HAGD
I'm trying to get file uploads working on my inventory system but can't seem to get it working. I am using Lite Uploader and PHP.
Here is my upload.php file:
<?php
require('../../includes/config.php');
$urls = array();
if (isset($_POST['liteUploader_id']) && $_POST['liteUploader_id'] == 'fileUpload1'){
foreach ($_FILES['fileUpload1']['error'] as $key => $error){
if ($error == UPLOAD_ERR_OK){
$uploadedUrl = $var['site_url'].'assets/images/uploads/' . $_FILES['fileUpload1']['name'][$key];
move_uploaded_file( $_FILES['fileUpload1']['tmp_name'][$key], $uploadedUrl);
$urls[] = $uploadedUrl;
}
}
if(file_exists($uploadedUrl)){
$message = "Successfully uploaded file.";
} else {
$message = "File did not upload properly.";
}
}
echo json_encode(
array(
'message' => $message,
'urls' => $urls,
)
);
exit;
?>
It appears that the file is not being moved once temporarily uploaded as there is no image shown on chrome when uploaded.
If you need any other files let me know. Thanks a lot!
EDIT:
Here is the upload form code:
<input type="file" name="fileUpload1" id="fileUpload1" class="fileUpload" />
<div id="details"></div>
<div id="response"></div>
<div id="previews"></div>
The form is done through javascript with the following code:
jQuery('.fileUpload').liteUploader({
script: 'libraries/lite_uploader/upload.php',
allowedFileTypes: 'image/jpeg,image/png,image/gif',
maxSizeInBytes: 250000,
customParams: {
'custom': 'tester'
},
before: function (files)
{
jQuery('#details, #previews').empty();
jQuery('#response').html('Uploading ' + files.length + ' file(s)...');
},
each: function (file, errors)
{
var i, errorsDisp = '';
if (errors.length > 0)
{
jQuery('#response').html('One or more files did not pass validation');
jQuery.each(errors, function(i, error)
{
errorsDisp += '<br /><span class="error">' + error.type + ' error - Rule: ' + error.rule + '</span>';
});
}
jQuery('#details').append('<p>name: ' + file.name + ', type: ' + file.type + ', size:' + file.size + errorsDisp + '</p>');
},
success: function (response)
{
var response = jQuery.parseJSON(response);
jQuery.each(response.urls, function(i, url)
{
jQuery('#previews').append(jQuery('<img>', {'src': url, 'width': 200}));
});
jQuery('#response').html(response.message);
}
});
I have a piece of code like that:
$(function() {
var uploader1 = new plupload.Uploader({
runtimes : 'gears,html5,flash,silverlight,browserplus',
browse_button : 'pickfiles1',
container : 'container',
max_file_size : '10mb',
url : 'upload.php',
flash_swf_url : '/plupload/js/plupload.flash.swf',
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
filters : [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
],
resize : {width : 320, height : 240, quality : 90}
});
uploader1.bind('Init', function(up, params) {
$('#filelist1').html("<div>Current runtime: " + params.runtime + "</div>");
});
$('#uploadfiles1').click(function(e) {
uploader1.start();
e.preventDefault();
});
uploader1.init();
uploader1.bind('FilesAdded', function(up, files) {
var temp_img_name = '';
$.each(files, function(i, file) {
$('#filelist1').append(
'<div id="' + file.id + '">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b> <input type="hidden" name="hdnPictureNameAddtemp" value="' + file.name + '"/>' +
'</div>');
if(temp_img_name == ''){
temp_img_name += file.name;
} else {
temp_img_name += ', ' + file.name;
}
});
$('#filelist1').append('<input type="hidden" name="hdnPictureNameAdd" value="' + temp_img_name + '"/>');
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('UploadProgress', function(up, file) {
$('#' + file.id + " b").html(file.percent + "%");
});
uploader1.bind('Error', function(up, err) {
$('#filelist1').append("<div>Error: " + err.code +
", Message: " + err.message +
(err.file ? ", File: " + err.file.name : "") +
"</div>"
);
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('FileUploaded', function(up, file) {
$('#' + file.id + " b").html("100%");
});
});
My problem is that I want to create a loop because some parts of the code above needs to be changed. In fact, uploader1, filelist1, pickfiles1, uploadfiles1 should be changed. Its last number should increase from 1 to n. I tried every thing to create a loop but it seems not work.
Also, this code is used to control the PLupload
Did not go through the whole logic, but one option should (roughly) be something like this (for 10 uploaders), concatenating the itemIndex to each selector. (watch out for the container item which does not seem to be indexed)
Server side, you may encounter the need to know which uploader triggered the upload. This might be solved, for example, with querystring parameters.
$(function() {
for (var itemIndex=1, itemIndex<10; itemIndex++)
initUploader(itemIndex);
});
function initUploader(itemIndex) {
var uploader1 = new plupload.Uploader({
runtimes : 'gears,html5,flash,silverlight,browserplus',
browse_button : 'pickfiles'+itemIndex,
container : 'container'+itemIndex,
max_file_size : '10mb',
url : 'upload.php',
flash_swf_url : '/plupload/js/plupload.flash.swf',
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
filters : [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
],
resize : {width : 320, height : 240, quality : 90}
});
uploader1.bind('Init', function(up, params) {
$('#filelist'+itemIndex).html("<div>Current runtime: " + params.runtime + "</div>");
});
$('#uploadfiles'+itemIndex).click(function(e) {
uploader1.start();
e.preventDefault();
});
uploader1.init();
uploader1.bind('FilesAdded', function(up, files) {
var temp_img_name = '';
$.each(files, function(i, file) {
$('#filelist'+itemIndex).append(
'<div id="' + file.id + '">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b> <input type="hidden" name="hdnPictureNameAddtemp" value="' + file.name + '"/>' +
'</div>');
if(temp_img_name == ''){
temp_img_name += file.name;
} else {
temp_img_name += ', ' + file.name;
}
});
$('#filelist'+itemIndex).append('<input type="hidden" name="hdnPictureNameAdd" value="' + temp_img_name + '"/>');
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('UploadProgress', function(up, file) {
$('#' + file.id + " b").html(file.percent + "%");
});
uploader1.bind('Error', function(up, err) {
$('#filelist'+itemIndex).append("<div>Error: " + err.code +
", Message: " + err.message +
(err.file ? ", File: " + err.file.name : "") +
"</div>"
);
up.refresh(); // Reposition Flash/Silverlight
});
uploader1.bind('FileUploaded', function(up, file) {
$('#' + file.id + " b").html("100%");
});
}
Below is my code I have everything working except dynamically linking the sliders to each input field. Here is my live page
<?php $dirname="panos/" ; $images=g lob($dirname. "*.jpg");
foreach($images as $image) {
$imageName=s ubstr($image, -14); echo '
<img src="resize.php?w=450&img='.$image. '" />
<input id="'.$imageName. '-slider"/>
<br />
<div style="width:450px" id="'.$imageName. '" class="slider"></div>
'; } ?>
<script>
$(function () {
$(".slider").each(function () {
$(this).slider({
value: 0,
min: 0,
max: 360,
step: 1,
stop: function (event, ui) {
var v = $(this).attr('id')
var n = $(this).slider('value')
$("#" + v + "-slider").val(n);
window.alert(v)
},
create: function (event, ui) {
var v = $(this).attr('name')
var n = $(this).slider('value')
$("#" + v + "-slider").val('0');
}
});
})
});
</script>
FIGURED IT OUT!!! The files that was getting pulled by the PHP had ".jpg" in the middle of it! And even tho it is a valid ID name it ended up messing up the jquery portion of it! I just did this
$imageNameLong = substr($image, -14);
$imageName = substr($imageNameLong,0 , -4);
and took off that ".jpg" and now it works flawlessly!!!