I'm using the blueimp File Upload Plugin with Yii to try and upload a file to my server (currently localhost). I gave the folder full read / write permissions (the location is C:\xampp\htdocs\yii), but I still get an error when I try to do the move_uploaded file command.
Here is the main form and input file area:
<form id='upload' method='post' action='?r=site/move' enctype='multipart/form-data' style="padding:0;">
<span class="btn fileinput-button" style="padding:0">
<i class="glyphicon glyphicon-picture">
<input id="fileupload" type="file" accept="image/*" name="attachment" onchange="attachAttachment()">
</i>
</span>
</form>
Here is blueimp's fileupload (in function()):
$("#fileupload").fileupload
({
dataType: 'json',
done: function (e, data)
{
console.log("YAY");
},
fail: function(e, data)
{
console.log("FAIL");
}
});
Here is the actionMove, where I move the file from the temp directory to the folder:
public function actionMove()
{
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0)
{
if (move_uploaded_file($_FILES['attachment'], Yii::getPathOfAlias('webroot')."/images/uploads")){
$response = '{"status":"success"}';
}
else {
$response = '{"status":"error"}';
}
echo $response;
exit();
}
}
I have been at this for hours now, any help is appreciated :(
$_FILES['attachment'] references all data about the download. move_uploaded_file uses filenames to work. Here is what you should try:
$uploadPath = Yii::getPathOfAlias('webroot')."/images/uploads";
$uploadFilename = basename($_FILES['attachment']['name']);
$tempFilename = $_FILES['attachment']['tmp_name'];
$ok = move_uploaded_file($tempFilename, $uploadPath.'/'.$uploadFilename);
if ($ok) {
$response = '{"status":"success"}';
} else {
$response = '{"status":"error"}';
}
More on this on the documentation pages:
http://php.net/manual/fr/features.file-upload.post-method.php
and
http://php.net/manual/fr/function.move-uploaded-file.php
Hope it helps.
Related
I am currently working with PHP on a web project with MVC architecture; the main task is to upload files in CSV format to a database in MariaDB. The project works without any problems, but there's a detail in which when the file is being uploaded, a blank screen is shown while it is being uploaded to the database; once the file is completely uploaded, the blank screen disappears and the interface is shown again with the respective success message that I added. Why is this happening? I don't handle large files, since with a relatively small file (8 KB) this appearance of a blank screen happens to me.
I had no problem with this detail at first, but now I want to show a .GIF image with a rotating ring so that the user knows that the upload process is taking place, but when the blank screen is displayed, I cannot find way of displaying said image. How could I stop showing the blank screen while uploading a file?
I attach my code:
VIEW (HTML):
<form role="form" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<input type="file" name="file" required/>
</div>
<input class="btn btn-primary" type="submit" name="import_file" value="IMPORT"/>
</fieldset>
<?php
$excel = new ControllerEvents();
$excel ->ctrImportExcel();
?>
</form>
CONTROLLER:
static public function ctrImportExcel()
{
if(isset($_POST["import_file"]))
{
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($data = fgetcsv($file_open, 1000, ",")) !== false)
{
$no_empleado = $data[0];
$date = $data[1];
$table = "events";
$answer = ModelEvents::mdlImportExcel($table, $data);
}
if($answer=="ok")
{
echo"<script>
Swal.fire({
title: 'Success!',
icon: 'success',
confirmButtonText:'Ok'
}).then((result)=>{
if(result.value){
window.location = 'index';
}
});
</script>";
}
else
{
echo"<script>
Swal.fire({
title: 'Error!',
icon: 'error',
confirmButtonText:'Ok'
});
</script>";
}
}
}
MODEL:
<?php
require_once "connection.php";
class ModelEvents{
static public function mdlImportExcel($table,$data)
{
$stmt = connection::connect()->prepare("INSERT INTO $table(employee,start_event) VALUES(:employee,:start_event)");
$stmt->bindparam(":employee",$data[0],PDO::PARAM_STR);
$stmt->bindparam(":start_event",$data[1],PDO::PARAM_STR);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt ->close();
$stmt = null;
}
?>
I'm going straight to the point here.
I'm trying to upload a 400mb+ zip file using jquery and codeigniter.
however, when the progress bar completes it gives me 500 Internal Server Error on the console log don't know what's causing this. I've tried it on my local files everything works fine. but when I put it online it gives me this 500 internal server error.
my hosting and my local have the same settings already.
upload_max_filesize 500M
post_max_size 500M
max_execution_time 3000
Here's my code:
HTML
<h1>Upload File</h1>
<hr />
<form method="post" name="upload_file" data-base-url="<?php echo site_url(array("main", "upload")); ?>" id="upload_file" action="<?php echo site_url(array("main", "do_upload")); ?>" enctype="multipart/form-data">
<p>File Type: <strong>(*)All</strong></p>
<!-- <p>File Type: <strong>doc, docx, pdf, xls, xlsx</strong> and <strong>txt</strong>.</p> -->
<input type="file" name="myfile" class="form-control" required><br>
<input type="submit" name="cmd_file_upload" id="cmd_file_upload" value="Upload File to Server" class="btn btn-default">
</form>
<br />
<p>File Uploaded: <?php echo $result['original_filename']; ?></p>
<div class="progress" style="display: none;">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
0% Complete (success)
</div>
</div>
JQUERY
$("#upload_file").on("submit", function(e){
e.preventDefault();
$("#cmd_file_upload").attr("disabled","disabled");
$(".progress").hide().show();
var $this = $(this);
var $url_transaction = $this.attr('action');
var $base_url = $this.data('base-url');
var formData = new FormData($this[0]);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$(".progress-bar").attr('style','width:'+percentComplete+'%');
$(".progress-bar").html(percentComplete+'%');
if (percentComplete === 100) {
$(".progress-bar").html(percentComplete+'% Complete (Success)');
}
}
}, false);
return xhr;
},
beforeSend:function(){
$(".progress-bar").attr('style','width:0%');
$(".progress-bar").html();
},
url: $url_transaction,
type: "POST",
data: formData,
contentType: false,
processData: false,
// dataType: "json",
success: function(result) {
console.log(result);
setTimeout(function(){
if(result == 0){
window.location.href = $base_url;
}else{
window.location.href = $base_url+"/"+result;
}
}, 500);
}
});
});
PHP CODE
public function do_upload(){
$filename = "file_".md5(date('Y-m-d H:i:s'));
$config['file_name'] = $filename;
$config['upload_path'] = './uploaded_files';
$config['allowed_types'] = '*';
// $config['allowed_types'] = 'doc|docx|pdf|xls|xlsx|txt';
$config['max_size'] = 500000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('myfile'))
{
$error = array('error' => $this->upload->display_errors('<span>','</span>'));
$err = array("status_id" => "0", "message" => $error['error']);
$_SESSION['type'] = "warning";
$_SESSION['message'] = $error['error'];
echo 0;
}
else
{
$data = array('upload_data' => $this->upload->data());
$prev_filename=$data['upload_data']['client_name'];
$file_ext = $this->upload->data("file_ext");
$new_filename = $filename.$file_ext;
$result = $this->main_m->insert_data('uploaded_file', array('original_filename' => $prev_filename, 'new_filename' => $new_filename));
$_SESSION['type'] = "success";
$_SESSION['message'] = "File's Successfully Uploaded!";
echo $result;
}
}
thanks in advance.
The first thing you should check is the permissions on the upload-to folder If it doesn't have read/write access (775 for example), then you'll get a 500 error.
If that doesn't work initially, I suggest you clear your browser cookies and cache, reload and try again. You should still rectify the 500000/512000k error however, it's an easy (and commonly-made ) mistake. In this instance you multiply 500 * 1024 ( kb in a mb) then by 1024 (b in a kb) to get 524,288,000
(b)
Ensure your post_max_size is greater than your upload_file_size and that your memory_limit is greater than the post_max_size (the default memory limit is 128MB)
Hope this helps.
I assume you're performing an AJAX request. If so, and if you're using Chrome, do not check console, but the Network tab. There, it should show you the last request made, with the headers, the response, the output and all that. Check there and tell us what you see first. That's the proper way to debug AJAX.
I need help with creating a progress bar for my php upload site. I've got the upload and exctract part sorted but i need help with the progress bar. I'm not sure how to do it. Also, is there a maximum file size for the upload?
HTML
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose file (.zip): <input type="file" name="zip_file" /></label>
<br />
<input type="submit" value="Upload" name="submit" value="Upload" />
</form>
PHP
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array(
'application/zip',
'application/x-zip-compressed',
'multipart/x-zip',
'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "[...] not a .zip file. Please try again.";
}
$target_path = "./".$filename;
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("./");
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
You can make some changes to fit but this works rather well if you want a progress bar. You can add more eventlisteners and make it how you want. I hope this is a good starting point for you.
function uploadFile(){
var file = document.getElementById("zip_file").files[0];
var formdata = new FormData();
formdata.append("zip_file", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", function(event) { runprogress(event); } , false);
ajax.addEventListener("load", function(event) {uploadcomplete(event); }, false);
//Target your php file.
ajax.open("POST", "upload.php");
ajax.send(formdata);
}
function runprogress(event){
//The progress %, you might want to Math.round(percent)
var percent = (event.loaded / event.total) * 100;
}
function uploadcomplete(event){
//This will = to your php reply.
var AjaxReply=event.target.responseText;
}
As far as I know you would have to use JavaScript to do this. Post your data through an AJAX call and initialize the progress bar. Over time animating it so that the bar "fills up".
Eventually the AJAX call will complete and will send a response back, upon the completion of the call you can finish the animation. This is how I would assume most progress bars work as they typically go up then stop around 99% until the post returns it's "complete status".
In any case, you would have a progress bar, represented by a <div> for example, with a width that would increase as time goes on, or a number would go up etc... and you would animate this using JavaScript and/or jQuery. Hopefully this will get you started in the right direction.
EDIT
Here's a link to a tutorial describing the steps necessary to upload files to the server using AJAX: Uploading Files with AJAX
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.
I have a full script of my php file.
Its a dataTable with a browse button to add new videos toe the Database and reload it in the DataTable
The problem is that the entry in the database is made, but the file never gets copied from its original location to the library/video folder.
I have tried and tried toe get it going by it seems like the part of php move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path) is never executed or something.
<?php
include 'config.php';
$sTable = "media";
$rootFolder = '../video/';
$libraryFolder = '../video/library/';
$priorityFolder = '../video/priority/';
if (!is_dir($rootFolder)) {
mkdir($rootFolder, 0777, true);
}
if (!is_dir($libraryFolder)) {
mkdir($libraryFolder, 0777, true);
}
if (!is_dir($priorityFolder)) {
mkdir($priorityFolder, 0777, true);
}
if(isset($_POST['script'])){
try {
$db = new PDO(
"mysql:host=".Config::$DB_HOST.";dbname=".Config::$DB_DATABASE.";charset=utf8",
Config::$DB_USERNAME,
Config::$DB_PASSWORD
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
print_r('CONNECTED TO DATABASE');
} catch(PDOException $e) {
print_r('ERROR CONNECTING TO DATABASE');
}
switch($_POST['script']){
case 'fetchAll':
$query = $db->prepare("SELECT * FROM $sTable");
$query->execute();
echo json_encode(array('media' => $query->fetch()));
break;
case 'insert':
$target = $_POST['file'];
$target_path = "../video/library/";
$target_path = $target_path . $target;
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". $target ." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
$data = array(
':name' => $target,
':path' => $target_path);
$table = 'media';
$fields = array('name', 'path');
$parameters = array(':name', ':path');
$param = implode(',',$parameters);
$stmt = $db->prepare("INSERT INTO {$table} (name, path) VALUES (:name, :path)");
try {
$db->beginTransaction();
$stmt->execute(array("$parameters[0]" => $data[':name'], "$parameters[1]" => $data[':path']));
$db->commit();
print $db->lastInsertId();
} catch(PDOExecption $e) {
$db->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
break;
default:
print_r('default');
break;
}
}
$db = null;
?>
<script>
$(document).ready( function () {
$('#vidlib_dtable').dataTable( {
"dom": '<"top"f>rt<"bottom"lp><"clear">'
} );
} );
</script>
<script>
$("#uploadedfile").on("change", function(){
var file = this.files[0];
var fileName = file.name;
var fileSize = file.size;
var fileType = file.type;
});
$(document).ready( function () {
$("#vidUpdSubmit").click(function() {
oFiles = document.getElementById("uploadedfile").files[0];
nFiles = oFiles.name;
nSize = oFiles.size;
var myFile = $('#uploadedfile').prop("files")['name'];
var url = "./inc/MediaScripts.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
data: ({'script':'insert',
'file': nFiles}
),
cache: false,
success:function(data){
alert(data);
},error:function(errormsg){
alert('EPPIC FAIL');
}
});
return false; // avoid to execute the actual submit of the form.
});
} );
</script>
<div class="site_window_header">File manager</div>
<div>
<div class="vl_buttonPane">
<form id="vidUpdForm" action="" method="POST">
<input type="hidden" name="sctipt" value="insert" id="sctipt"/>
Choose a file to upload: <input name="uploadedfile" id="uploadedfile" type="file" /><br />
<input type="submit" id="vidUpdSubmit" value="Upload File" />
</form>
</div>
<div class="vl_rightPane">
<table id="vidlib_dtable" class="display">
<thead>
<tr>
<th>Name</th>
<th>Title</th>
<th>File path</th>
<th>Duration</th>
<th>Date uploaded</th>
<th>Uploaded by</th>
<th>Key words</th>
<th>Comments</th>
</tr>
</thead>
</table>
</div>
</div>
HERE is a link to a dropbox zip file with a manageable working copy of the program
SOLUTION: thanks to -> Alexander Ceballos
Upload Multiple Files with PHP and JQuery
So the problem isn't with $_FILES the problem is that you are not submitting the file. You are using ajax to post the file name(nfiles) and the value 'insert' with data:({'script':'insert', 'file':nfiles})which allows your script to process the the table update. However, you aren't actually posting the file since the form isn't being submitted, so $_FILES['uploadedfile] is actually undefined. You either need to actually submit the form and then you will be able to handle moving your file in the way your script is currently written. Or you need to add the file to your ajax post which will require you to create a form data object var formData = new FormData();. Check this page out for more on uploading files with ajax or have a look at this example. Hope this helps.