I am using an old script I used on previous projects to upload images. The project only used HTML and PHP making uploading easier to handle as such! :)
I am quite new to Jquery and Ajax handlers and due to my current projects high use of handlers I need to upload things without refreshing entire page, perhaps just a div.
My Script:
function postfile() {
var filename = $("#image").val();
$.ajax({
type: "POST",
url: "pages/minutes1.php",
secureuri:false,
fileElementId:'image',
enctype: 'multipart/form-data',
data: "submit=yes&image=" + {file: filename},
success: function(msg5){
$("#upform").html(msg5);
}
});
}
My PHP and HTML:
<?
/**
* The following uploader was not originally suited for text based files<br>
* Copied and Re-used from previous projects<br>
*/
$submit = $_POST['submit'];
if($submit=="yes")
{
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","100");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an error occurs.
//If the error occurs the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
if(!$image){
?>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="tabcol1 font1" style="text-align: center;">
There was no minutes file attached!
</td></tr>
<tr>
<td class="tabcol4 font1" style="text-align: center;">
Please wait as you are directed back
</td></tr>
</table>
<?
}elseif($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
if (($extension != "doc") && ($extension != "txt") && ($extension != "pdf") && ($extension != "odt") && ($extension != "docx") && ($extension != "rtf"))
{
?>
<b>The file type uploaded is not supported!</b><br><br>
<b>Supported formats:</b> doc, docx, pdf, odt, txt, rtf
<?
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
?>
File size, too large! (if you need lieniency please contact webmaster)
<?
}else{
//we will give an unique name, for example the time in unix time format
$exam = substr("$filename", 0, -2);
function MakeRandom($minLength, $lastNr){
$i = 0;
while ($i <= $minLength){
$randomnr = ($i === $minLength) ? 1 : rand(0, 9);
$strNumber = (!$strNumber) ? $strNumber = $randomnr : $strNumber .= $randomnr;
$i++;
}
return $strNumber;
}
// show the number
$num = MakeRandom(5, 1);
$col = "$exam$num";
$image_name = $col.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="minutes/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied){
?>
File uploaded and E-mail sent!
<?
}
}
}
}
}else{
?>
<div id="upform">
<form method="post">
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="font1 tabcol1">
<!-- begin 2 column table -->
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="font1">
<b>Choose a file to upload:<br> <input id="image" name="image" type="file" /><br />
<input type="button" id="submit" name="submit" value="submit" onclick="postfile()">
</td>
<td class="font1"></td>
</tr>
</table>
<!-- End 2 column table -->
</td></tr>
</table>
</form>
</div>
<?
}
?>
The problem I am getting is, even when I have added a file and pressed submit,
it gives me my no image error.
I believe I have written the script wrong but I could not find any syntax errors.
All help would be appreciated!
Thank you in advance :)
$.ajax doesn't support file uploads the same way that a normal form submission does. The usual suggestion to get around this is to embed your upload script into an iframe so it doesn't reload the page when you upload.
Here's an example.
Related
The Form:
<div id="maindiv">
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
</div>
</div>
The Script:
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This script also uses javascript for multiple image upload.
When clicking on "page reload" in the web browser, after the first upload has been done, then the script assigns the same file a new ID code for the name and moves the image files a second time into the "uploads" folder.
How to prevent the script from moving the image files (with a new ID code assigned for the name) a second time into the "uploads" folder?
Any suggestions are much appreciated.
EDIT:
So, I opted for a "redirect" to the same page, where the form gets cleared out, after the submission has been done.
It looks like, this is the way to do it.
Before upload (where you displays the upload FORM) you can create a key (random) and store it on your server somehere. (temp folder) (using a serial number is even more safe)
You can include this as "hidden" value in the upload form.
The script, which is processing the upload, should look first for this key, if it exists, you can delete it and proceed with the rename / upload / whatever you want to do.
If the key is gone, you can be sure it's a duplicated request and simply ignore it.
Don't forget to clean your temp folder every time (let's say delete every keys which is older than an hour or so)
I am writing a code for uploading one excel file.And displaying its full content on a webpage.But whenever user clicks on the submit button it shows the error-
"Your File Type is:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
File type must be text(.txt) or msword(.doc)."
Below is my code.
<?php
if( isset($_POST['submit1'])) {
// $_FILES is the array auto filled when you upload a file and submit a form.
$userfile_name = $_FILES['file1']['name']; // file name
$userfile_tmp = $_FILES['file1']['tmp_name']; // actual location
$userfile_size = $_FILES['file1']['size']; // file size
$userfile_type = $_FILES['file1']['type'];
$userfile_error = $_FILES['file1']['error']; // any error!. get from here
// Content uploading.
$file_data = '';
if ( !empty($userfile_tmp))
{
$file_data=base64_encode(#fread(fopen($userfile_tmp,'r'), filesize($userfile_tmp)));
}
switch (true)
{
// Check error if any
case ($userfile_error == UPLOAD_ERR_NO_FILE):
case empty($file_data):
echo 'You must select a document to upload before you can save this page.';
exit;
break;
case ($userfile_error == UPLOAD_ERR_INI_SIZE):
case ($userfile_error == UPLOAD_ERR_FORM_SIZE):
echo 'The document you have attempted to upload is too large.';
break;
case ($userfile_error == UPLOAD_ERR_PARTIAL):
echo 'An error occured while trying to recieve the file. Please try again.';
break;
}
if( !empty($userfile_tmp))
{
// only MS office and text file is accepted.
if( !(($userfile_type=="application/msword") || ($userfile_type=="text/plain") || ($userfile_type=="application/vnd.ms-excel")) )
{echo 'Your File Type is:'. $userfile_type;
echo '<br>File type must be text(.txt) or msword(.doc).';
exit;
}
}
echo filesize($userfile_tmp);
}
?>
<HTML>
<HEAD>
<TITLE> PHP File Upload Script </TITLE>
</HEAD>
<BODY>
<form name="profile" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" target="_self" enctype="multipart/form-data" >
<P align ="center"><input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input name="file1" type="file" accept="application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" />
<input type="submit" name="submit1" value="Submit" />
</P>
</form>
</BODY>
</HTML>
Please help .
Thank you in advance.
You need to add following in your if condition as well
because your are checking for application/vnd.ms-excel and application/msword but file is having its header different as
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetyour" So if you add this inside if like
if(($userfile_type=="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetyour") || ($userfile_type=="application/msword") || ($userfile_type=="text/plain") ||
($userfile_type=="application/vnd.ms-excel")){
// code
}
Because server will interpret the file type based on headers it receives.
If you want to show Excel file contents on your page then you should think of using PHPExcel. It is very easy to use.
Link: https://phpexcel.codeplex.com/
Examples: https://phpexcel.codeplex.com/wikipage?title=Examples&referringTitle=Home
I'm making an uploader for a website which is designed to upload videos. As of now, it doesn't check if they're videos, it's simply uploads them. I do this through a simple form that selects a file and submits it to upload.php. Here is the HTML which I do this with:
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();">
Video Name: <input type="text" name="name" class="maininput" style="width:300px;" maxlength="80"><br>
File: <input name="myfile" type="file" class="mainbutton"/ style="clear:both;"><br>
Description: <br><textarea cols="43" rows="10"></textarea><br>
<input type="submit" name="submitBtn" value="Upload" class="mainbutton"/>
</form><br><br><br>
<p id="f1_upload_process">Loading...<br/><img src="/images/loader.gif" width="20" height="20" /></p>
<p id="result"></p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;">
<script language="javascript" type="text/javascript">
window.top.window.stopUpload(<?php echo $result; ?>);
</script> </iframe>
Here are my javascript functions which accompany this:
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
document.getElementById('result').innerHTML =
'<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
document.getElementById('result').innerHTML =
'<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
return true;
}
And finally, here is the contents of upload.php, which I use for actually uploading the file:
<?php
$result = 0;
$target_path = "videos/";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
I believe that the issue is with the upload.php. The problem is not with anything client side, it's the fact that in the client, it uploads the file, but I can't find the file in the videos folder, or any folder in the server directory.
Any help is greatly appreciated. Thanks!
This is what I use, you can customize it to suit your script:
Simply change the *path and *variables.
<?php
// Configuration - Your Options
$allowed_filetypes = array('.mov','.mp3','.mp4','.flv'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
I was working on a simple file upload exercise i've gotten from my WebDev Class - We actually only had to copy the code and integrate it to fit our needs.
I tried to do so for my project, sadly it will keep on echoing out the same error.
<?php
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg');
$max_filesize = 524288;
$upload_path = 'uploads/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
var_export($_FILES, $ext);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['usrfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here';
else
echo 'There was an error during the file upload. Please try again.';
?>
It keeps on giving me the 'wrong filetype' error, with all of defined types in the array.
<form id='upload' action="uploadfile.php" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td >Choose a File to Upload</td>
</tr>
<tr>
<td >Select File</td>
<td ><input type="file" name="userfile"></td>
</tr>
<tr>
<td colspan=2 id="sub"><input type="submit" name="submit" value="submit" ></td>
</tr>
</Table>
</form>
$filename = $_FILES['usrfile']['name'];
The 'tmp_name' index contains a temporary file name, not the one the file really had. That's stored in 'name'. See this page for information.
Additionally, you should:
check for errors in the 'error' index.
use pathinfo to get the extension,
lowercase it before searching the array,
add some randomness to the uploaded file name to avoid overwriting existing files.
You can use this as firstly you have to always echo the $_FILES array then start debuging.
change this line from
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg');
to
$allowed_filetypes = array('jpg','gif','bmp','png', 'jpeg');
change the follwing line
if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
to
if(filesize($_FILES['usrfile']['size']) > $max_filesize)
and remove the line
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
and change this line
if(!in_array($ext,$allowed_filetypes))
to
if(!in_array($_FILES['usrfile']['type'],$allowed_filetypes))
Due-diligence done, once again I return to the experts. Please forgive my ignorance, new to all this.
I'm trying to create a form which allows users to:
Insert the values of various form fields into a mysql database table - Easy, no issues here.
Attach a file which is saved within the file structure (in a folder called 'documents').
Save the file name, size, type (pdf, txt, etc.) to the same record.
After a file is uploaded the table would contain:
id (auto incremented)
name (text field, user generated)
description (text field, user generated)
File name (e.g. text.txt, added automatically on upload)
File size (e.g. 362455[kb], added automatically on upload)
File type (e.g. pdf, added automatically on upload)
I've successfully saved files to the folder but have not been able to make my three requirements a reality... Despite hours or troubleshoot and Googling.
The database and form are correct, the php file I post to is the mystery. Any ideas?
<form method="post" id="addForm" action="includes/insert_news.php">
<table class="addForm" cellspacing="0">
<tr>
<th>Name:<span class="greenText">*</span></th>
<td><input name="name" type="text" class="textBox required" value="Friendly Document Name" maxlength="80" /></td>
</tr>
<tr>
<th>Description:<span class="greenText">*</span></th>
<td><textarea name="description" class="textBox required">Document description blah blah</textarea></td>
</tr>
<tr>
<th>File:</th>
<td><input name="file" class="textBox" /></td>
</tr>
<tr>
<th> </th>
<td><input type="image" class="button" src="images/button_submit.gif" /></td>
</tr>
</table>
I am wondering you said that
I've successfully saved files to the
folder but
but I think you are not getting anything in the $_FILES because this thing is missing in your form tag
<form enctype="multipart/form-data">
Assuming that you have already added the missing thing #shakti pointed out, and you change the <input> by adding type="file" and since you didn't give any information about your php code, try these out:
<?php
class UploadFile{
//declare some variables in corresponding to your database field here, like fields, table name and stuffs
public function attach_file($file) {
if($file['error'] != 0) {
//do something
} else {
$this->temp_path = $file['tmp_name'];
$path_parts = pathinfo($file['name']);
$this->filename = $path_parts['extension'];// to get the filename
$this->type = $file['type'];// to get the file type
$this->size = $file['size'];// to get the size
$this->name = $name;
$this->description = $description;
}
}
public function save() {
$target_path = "/some/folder";
if(move_uploaded_file($this->temp_path, $target_path)) {
if($this->create()) {
unset($this->temp_path);
return true;
}
} else {
return false;
}
}
public function create() {
//your INSERT INTO
}
?>
and in your insert_news.php :
<?php
require_once("class/location");
if($_FILES['file']) {
$news = new UploadFile();
$news->attach_file($_FILES['main_picture'], $_POST['name'], $_POST['description']);
if($pic->save()){
//do something
}
}
?>
haven't tested this, but i hope you get the point :D