I've been trying to create a registration form that requires students to upload documents at the very end. However, after picking up the form values via jQuery, the PHP document can't seem to pick up my uploaded form. Any ideas?
Form:
<form id="joinUs" enctype="multipart/form-data" method="post">
<!--various form fields-->
<input type="file" name="transcript" id="transcript">
<div class="button" id="submit">Submit!</div>
</form>
jQuery:
$("#submit").click(function(){
//firstName, lastName, grade, studentID, email, phone are all form values
var data = "firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
$.ajax({
type: "POST",
url: "join_submit.php",
data: data,
success: function() {
location.href="http://mvcsf.com/new/success.php";
}
});
join_submit.php
$allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts";
$filename = $_FILES["transcript"]["name"];
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
if ($_FILES["transcript"]["error"] > 0) {
echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
}
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}
I ran this, and I got no errors. I also tried to print out the file name, except nothing printed out.
This should do it for you :
$("#submit").click(function () {
var transcript = $("#transcript").val();
var data = "firstName=" + firstName + "&lastName=" + lastName + "&grade=" + grade + "&studentID=" + studentID + "&email=" + email + "&phone=" + phone;
var formData = new FormData();
formData.append("file", transcript);
formData.append("data", data);
$.ajax({
type: "POST",
url: "join_submit.php",
enctype: 'multipart/form-data',//optional
cache: false,
contentType: false,
processData: false,
data: {
file: file
data: data
},
success: function () {
location.href = "http://mvcsf.com/new/success.php";
}
});
});
Cheers
First, In your code, you are posting data with $.ajax({...}) and the data sent is
"firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
There is no transcript at all.
Secondly, and most important, you cannot post file with $.ajax({...}) like that, it will not working like that. As #Roy M J says, you should take a look at FormData (for recent browser only), or take a look on the web for an upload jQuery plugin (don't re-invent the whell, some good plugin already exists :))
Take a look here
You cannot send a file like you do the values of HTML elements. There are two methods to file upload, the one I've used successfully is the AJAX method using a third-party feature called 'AjaxUploader'.You can download it here via GitHub. Once you've done it, add the ajaxuploader.js file in your 'js' folder (or wherever you've put all of your script files), include the file in the HTML page where you've to use the uploader. Now, uploading is as simple as follows.
HTML:
<input type="file" name="transcriptUploader" id="transcriptUploader" value="Upload" />
jQuery (you need to have the jQuery file included in your page):
new AjaxUpload('transcriptUploader', {
action: "page_to_handle_upload.php", // You need to have either a separate PHP page to handle upload or a separate function. Link to either one of them here
name: 'file',
onSubmit: function(file, extension) {
// This function will execute once a user has submitted the uploaded file. You can use it to display a loader or a message that the file is being uploaded.
},
onComplete: function(file, response) {
// This function will execute once your file has been uploaded successfully.
var data = $.parseJSON(response); // Parsing the returning response from JSON.
if(data.error == 0)
{
// If the file uploaded successfully.
}
else if(data.error == "size"){
// If the response object sent 'size' as the error. It means the file size exceeds the size specified in the code.
}
else if(data.error == "type"){
// If the response object sent 'type' as the error. It means the file type is not of that specified in the code (in your case, pdf).
}
else{
// In case the file didn't upload successfully or the code didn't return a usual error code. It is still an error so you need to deal with it appropriately.
}
}
});
Your back-end PHP code that will be doing all the heavy lifting (uploading the file, checking extensions, moving it etc):
if(isset($_FILES)) // Checking if a file is posted.
{
if ($_FILES['file']['error'] == 0) //Checking if file array contain 0 as an error. It means AJAX had no error posting the file.
{
$response = array(); // Initializing a new array.
$allowedExts = array("pdf"); // Allowable file format.
$filename = stripslashes($_FILES['file']['name']); // Storing file name.
//$extension = strtolower(self::_getExtension($filename)); // Fetching file extension.
// Code block to extract file extension and storing it in a variable called $extraction.
$i = strrpos($str, ".");
if (!$i)
{
$extension = "";
}
$l = strlen($str) - $i;
$extension = strlower(substr($str, $i + 1, $l));
$size = $_FILES['file']['size']; // Storing file size (in bytes).
$fileNameAfterUpload = md5((time() + microtime())) . '.' . $extension; // Concatinating file name and extension.
$baseSystemPath = "/var/www/<your_folder_name>/uploaded_transcripts/" // Path on which the file will be uploaded. Need to be relative web path.
$maxSize = 10*10*1024; // Storing file size. Be advised the file size is in bytes, so this calculation means max file size will be 10 MB.
$webPath = "uploaded_transcripts/". $filename; // Creating web path by concatinating base web path (the folder in which you'd be uploading the pdf files to) with file name.
if (in_array($extension, $allowedExts)) // Checking if file contains allowabale extensions.
{
if($size <= $maxSize) // Checking if the size of file is less than and equal to the maximum allowable upload size.
{
$moved = move_uploaded_file($_FILES['file']['tmp_name'], $webPath); // Moving the file to the path specified in $webPath variable.
if($moved == true)
{
$response['error'] = 0; // If moved successfully, storing 0 in the response array.
$response['path'] = $webPath; // Storing web path as path in the response array.
$response['filename'] = $filename; // Storing file name in the response array.
}
else
{
$response['error'] = 'internal'; // If move isn't successfull, return 'internal' to AJAX.
}
}
else
{
$response['error'] = 'size'; // If file size is too small or large, return 'size' to AJAX.
}
}
else
{
$response['error'] = 'type'; // If file type is not that of defined, return 'type' to AJAX.
}
echo json_encode($response); // Returning the response in JSON format to AJAX.
}
}
Do let me know if you need further assistance.
P.S: Don't forget to mark it as an answer if it worked.
Related
The concept is pretty simple, I need to upload a file without refreshing the page, so I'm using an ajax. I've never done an upload ajax before, so I'm not sure what I'm missing here.
function uploadAttachment(){
var name = document.getElementById("file").files[0].name;
var did = <? echo $did ?>;
var form_data = new FormData();
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("File Size is too large. Please make sure your file's size is less than 2MB.");
}
else
{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax
({
url:"/assets/ajax/disciplinaries_upload.php?did="+did,
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function()
{
$('#uploaded_file').html("<label class='text-success'>File Uploading...</label>");
},
success:function(data)
{
$('#uploaded_file').html(data);
}
});
}
};
And my disciplinaries_upload.php ajax as follows;
<?php
$did = $_GET['did'];
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$fname = reset($test);;
$ext = end($test);
$name = $fname . '_' .$did. '.' . $ext;
$location = '/assets/uploads/files/disciplinary_attachments/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
if (file_exists($location)) {
echo '<label class="text-success">File Uploaded Successfully</label>';
} else {
echo '<label style="color: red">File Upload Failed</label><br> Original File Name: '.$_FILES["file"]["name"].'<br> Extension: '.$ext.'<br> Newly Generated Name: '.$name.'<br>File Location: '.$location;
}
}
?>
The problem seems to be that it's not actually uploading the file. I'm receiving the upload failed error that I've created which looks as follows;
File Upload Failed
Original File Name: test.txt
Extension: txt
Newly Generated Name: test_25.txt
File Location: /assets/uploads/files/disciplinary_attachments/test_25.txt
So by the looks of it, it does actually receive the file and knows where it needs to go... it just doesn't actually upload it there.
Thanks to both #Jay Blanchard and #kerbholz the code now works. All I had to do was change
$location = '/assets/uploads/files/disciplinary_attachments/' . $name;
to
$location = '/usr/www/users/keepnxcanc/assets/uploads/files/disciplinary_attachments/' . $name;
Looks like this issue might happen because of Upload file size limitation and type or Destination write permeation or Destination path is not satisfying or file upload over http/https is blocked by security team.
Solution:
Upload file size limitation: By default web servers might allow to upload up to 1MB. you need to change the property called Max_upload_size to you requirement.
Destination write permeation: Some times we might forgot to remove wright protection to upload destination folder. So, Change the permissions to disable wright protection of the destination folder.
Destination path is not satisfying: Some times the destination path might not clear to make changes in. So, better to provide complete path.
code snip1: place at the top of you logic in index.php
define("BASE_PATH", __DIR__);
code snip2: change this $location in disciplinaries_upload.php
$location = BASE_PATH . '/assets/uploads/files/disciplinary_attachments/' . $name;
File upload over http/https: if your security team is enabling any restrictions, as them to enable. or make your self whitelist.
finally: a slight change in your code.
Code snip:
<?php
//comment this two lines in production
error_reporting(E_ALL);
ini_set('display_errors', 1);
//define("BASE_PATH", __DIR__); //if both index.php and disciplinaries_upload.php in same location, comment this else keep it in index.php
$did = $_GET['did'];
if(count($_FILES) > 0)
{
$test = explode('.', $_FILES["file"]["name"]);
$fname = reset($test);;
$ext = end($test);
$name = $fname . '_' .$did. '.' . $ext;
$location = BASE_PATH . '/assets/uploads/files/disciplinary_attachments';
$permition_cod = substr(sprintf('%o', fileperms($location)), -4);
#chmod($location, "0777");
if (move_uploaded_file($_FILES["file"]["tmp_name"], $location.'/'.$name)) {
echo '<label class="text-success">File Uploaded Successfully</label>';
} else {
echo '<label style="color: red">File Upload Failed</label><br> Original File Name: '.$_FILES["file"]["name"].'<br> Extension: '.$ext.'<br> Newly Generated Name: '.$name.'<br>File Location: '.$location;
}
#chmod($location, $permition_cod);
}
?>
Good luck...
Hi i have the following code that uploads videos to a server and updates the database accordingly. This code works fine when i run it with a bunch of images and or small video's. See the code below:
for ($i=0; $i<count($_FILES['images']['error']); $i++) {
if ($_FILES['images']['error'][$i] == UPLOAD_ERR_OK) {
$tmpName = $_FILES['images']['tmp_name'][$i];
$name = $_FILES['images']['name'][$i];
$type = $_FILES['images']['type'][$i];
if (strpos($type, 'image') !== false) {
$type = "img";
}elseif(strpos($type, 'video') !== false){
$type = "vid";
}else{
exit();
}
move_uploaded_file(($tmpName), $dir.$name);
$upload = array(
'name'=>$name,
'type'=>$type
);
$uploads[] = $upload;
}
}
But when my client tries to upload a video bigger than 64mb the program doesnt upload it... I already tried to change the max_file_size and other according parameters to allow bigger files. But my clients hosting provider doesnt allow this.
So are there any other ways of uploading big files to my server via my custom cms?
Thomas
So as said in comments. Reference material is below code examples. Trick is to cut the file into chunks that are less than the upload limit. This method can be extended to the point that when a file upload is interrupted you can continu on the last known part. :-)
Basic JavaScript class to assist in uploading the file, determines the chunks to be sent to a PHP server.
function fileUploader() {
// Called when the file is selected
this.onFileSelected = function() {
// Read file input (input type="file")
this.file = this.fileInput.files[0];
this.file_size = this.file.size;
this.chunk_size = (1024 * 1000);
this.range_start = 0;
this.range_end = this.chunk_size;
this.slice_method = 'slice';
this.request = new XMLHttpRequest();
// Start uploading
this.upload();
};
this.upload = function()
{
var self = this,
chunk;
// Last part reached
if (this.range_end > this.file_size) {
this.range_end = this.file_size;
}
// Chunk the file using the slice method
chunk = this.file[this.slice_method](this.range_start, this.range_end);
// Open a XMLHttpRequest
var endpoint = "/url/to/php/server/for/processing";
this.request.open('PUT', (endpoint));
this.request.overrideMimeType('application/octet-stream');
this.request.send(chunk);
// Make sure we do it synchronously to prevent data corruption
this.request.onreadystatechange = function()
{
if (self.request.readyState == XMLHttpRequest.DONE && self.request.status == 200) {
self.onChunkComplete();
}
}
};
this.onChunkComplete = function()
{
if (this.range_end === this.file_size)
{
// We are done, stop uploading
return;
}
this.range_start = this.range_end;
this.range_end = this.range_start + this.chunk_size;
this.upload();
};
}
And for the PHP bit:
...
$out = fopen("{$filePath}.partial", "a+");
fwrite($out, file_get_contents("php://input"));
fclose($out);
...
Big warning here, make sure to properly validate and take security measures to ensure the safety of your clients upload function. You are writing the raw PHP input to a file.
When the upload is done you can rename the file to it's original name including the correct extension.
Reference material:
http://creativejs.com/tutorials/advanced-uploading-techniques-part-1/index.html
https://secure.php.net/manual/en/wrappers.php.php
In a nutshell.. it's break the file into small chunks using a processor, upload the files using conventional methods (like you would normally upload a file), append the input to a temporarily file. Some pitfalls I encountered were sending extra params and alike to the endpoint, avoid those as it's appended to the file and it will corrupt your file.
I am using quilljs for my editor. All my data are handle by mysql database. I am using Angularjs 1.x and for backend Cakephp is my frame-work.
I am currently trying to build a forum kind of page in which I want to save multiple images along with text which will be formatted using quilljs
<p>sd<img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgA....SUVORK5CYII=" alt="i am image"><b>it is image of earth</b></p>
This is what currently storing in my database. Now if there is multiple big images come in then size of field will be too much high there for I want to upload image inside severside folder and want to print image address inside image tag like:
<p>sd<img src="../img/709f2d0be9d13c645037f1b9bb066b00a6d7/image1.jpg" alt="i am image"><b>it is image of earth</b></p>
So I can fetch image directly from given folder.
i have done small trick with quilljs. i have put some code inside quilljs which send image toward my php script on line number 8663 after if (typeof value === 'string') this statement i have added script which sends image value to my php script
var img = {
'img' : value
}
$.ajax({
url: "../Writers/writerCertificateupload",
data: img,
contentType: undefined,
type: 'post'
}).success(function(path){
node.setAttribute('src', path);
})
where node.setAttribute('src', path); sets path which i am returning from php script it sets it on image tag i.e <img src="../img/709f2d0be9d13c645037f1b9bb066b00a6d7/image1.jpg">
and then it sets it inside editor and then we can save that data within editor. this is how i have solve this problem.
my php code is
public function writerCertificateupload()//pending
{
$id = $this->Auth->user('id');
$this->autoRender=false;
define('UPLOAD_DIR', 'files/post/');
$img = $_POST['img'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
$file = "../".$file;
print $success ? $file : 'Unable to save the file.';
}
You need to create custom image handler (like here) and check base64 string length with fileReader.
I had the same problem in Angular(primeNg) and ended up with the below solution, Btw plz notice that you only need to monitor the editor text change and do some modification like below:
public async handleTextChange(event: any) {
try {
const operations = event.delta.ops;
for (let i = 0; i < operations.length; i++) {
const op = operations[i];
const opType = Object.keys(op)[0] as any;
if (opType == 'insert' && op['insert'].hasOwnProperty('image')) {
this.isLoading = true;
const uploadedImageURL = await this.uploadImage(op['insert'].image);
this._cdr.detectChanges();
const newContent = event.htmlValue.replace(
op['insert'].image,
uploadedImageURL
);
this.editorContent = newContent;
this.contentChanged.emit(newContent);
}
}
} catch (error) {
this.editorContent = this.editorContent + '<br/><br/>';
} finally {
this.isLoading = false;
this._cdr.detectChanges();
}
The upload method will be like this, by the way the upload logic will be depends on your own logic though more or less it's the same:
async uploadImage(dataURL: string): Promise<string> {
const ImageData: FormData = new FormData();
let fileType = dataURL.substring(
dataURL.indexOf(':') + 1,
dataURL.lastIndexOf(';')
);
let fileExtension = fileType.split('/');
const file = new File(
[dataURL],
`file${new Date().getTime()}.${fileExtension[1]}`,
{ type: fileType }
);
ImageData.append('file', file);
const uploadedImageURL = await this._imageUploaderService
.uploadedImage(ImageData)
.toPromise();
return uploadedImageURL ;
}
The component html would be like this
<p-editor
name="editorContent"
[(ngModel)]="editorContent"
[id]="editorId"
[style]="{ height: '320px' }"
(onTextChange)="handleTextChange($event)"
></p-editor>
<app-spinner *ngIf="isLoading == true"></app-spinner>
It's worth mentioning that I used this for p-editor which belongs to primeNg in angular projects
how can i show and delete previously uploaded files with the great bootstrap-fileinput plugin from krajee, my code is:
html:
<script>
$("#images").fileinput({
uploadAsync: true,
uploadUrl: "upload.php"
}).on("filebatchselected", function(event, files) {
$("#images").fileinput("upload");
});
</script>
upload.php:
<?php
if (empty($_FILES['images'])) {
echo json_encode(['error'=>'No files found for upload.']);
return;
}
$images = $_FILES['images'];
$success = null;
$paths= [];
$filenames = $images['name'];
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . basename($filenames[$i]);
if(move_uploaded_file($images['tmp_name'][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
if ($success === true) {
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
echo json_encode($output);
?>
Has anyone an idea ? i think i have to scan the uploads dir and send it back with json or use $output, but i dont know how to this ?
Since you are using json to upload files, you can use it to delete them too. Make another ajax call to the server by sending an array of the image URLs that you want to remove. Then with PHP you can simply unlink them.
So for example: http://jsfiddle.net/fdzsLa0k/1/
var paths = []; // A place to store all the URLs
// Loop through all images
// You can do it for a single image by using an id selector and skipping the looping part
$('.uploaded-img').each(function(i, v) {
paths.push(this.src); // Save found image paths
})
console.log(paths); // Preview the selection in console
// Send the URLs to the server for deletion
$.ajax({
method: 'post',
data: { images: paths },
url: 'ajax.php' // Replace with your ajax-processing file
}).success(function(response) {
console.log(response); // Do fun stuff: notify user, remove images from the loaded HTML
});
uuuhh, the fileinput script need php version higher than 5.3.3, because the plesk panel of my hosting provider supports only 5.3.3 i have the problems, since 11.5 plesk supports multiple php version for each domain on the server, now with php 5.6 everything works great !
I am working on a multiple file uploader using HTML5's FormData and jQuery. I have the following code:
$(function() {
$('#file').bind("change", function() {
var formData = new FormData();
//loop for add $_FILES["upload"+i] to formData
for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
formData.append("file" + i, document.getElementById('file').files[i]);
}
//send formData to server-side
$.ajax({
url : "file-upload.php",
type : 'post',
data : formData,
dataType : 'json',
async : true,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
error : function(request) {
alert('error!!');
console.log(request.responseText);
},
success : function(json) {
alert('success!!');
$('#upload-result')[0].append(json);
}
});
});
});
I can see that my file-upload.php works fine because the files are uploaded! But why does my jQuery hit the error function and not the success function? I get an alert of Error.
In the console window, I see the result of my PHP echo call! Which I want to append to #upload-result as shown in my success function.
PHP code
foreach($_FILES as $index => $file)
{
$fileName = $file['name'];
// echo '[ file name: ' . $fileName . ' - ';
$fileTempName = $file['tmp_name'];
// echo 'file temp name: ' . $fileTempName . ' ]';
if(!empty($file['error'][$index]))
{
// some error occured with the file in index $index
// yield an error here
return false; // return false also immediately perhaps??
}
// check whether it's not empty, and whether it indeed is an uploaded file
if(!empty($fileTempName) && is_uploaded_file($fileTempName))
{
// the path to the actual uploaded file is in $_FILES[ 'file' ][ 'tmp_name' ][ $index ]
// do something with it:
move_uploaded_file($fileTempName, "uploads/" . $fileName);
echo json_encode('<p>Click here to download file!</p>');
}
}
I figured it out. I was getting the jQuery AJAX error even though my status code was 200 for the php file because I had my dataType as JSON, whilst I was returning simple HTML.
dataType: 'html',
Fixed it!
Thanks all.