AJAX/Laravel Multiple File Uploads - php

I'm trying to upload multiple files from a drag/drop event using jQuery/AJAX/Laravel.
MY DROP EVENT:
$( document ).on('drop dragleave', '.file-drag', function(e){
$(this).removeClass('drop-ready');
if(e.originalEvent.dataTransfer.files.length) {
e.preventDefault();
e.stopPropagation();
if (e.type === "drop") {
var files = e.originalEvent.dataTransfer.files;
AjaxFileUpload(files)
}
}
});
MY UPLOAD SCRIPT:
function AjaxFileUpload(files){
console.log(files);
//Start appending the files to the FormData object.
var formData = new FormData;
formData.append('_token', CSRF_TOKEN);
for(var i = 0; i < files.length; i++){
formData.append(files[i].name, files[i])
}
console.log(formData.entries());
$.ajax({
//Server script/controller to process the upload
url: 'upload',
type: 'POST',
// Form data
data: formData,
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Error logging
error: function(jqXHR, textStatus, errorThrown){
console.log(JSON.stringify(jqXHR));
console.log('AJAX Error: ' + textStatus + ": " + errorThrown);
},
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
success: function(data){
console.log(data);
}
});
}
MY CONTROLLER CODE:
class UploadsController extends Controller
{
public function UploadFiles(Request $request){
return $request->all();
}
}
I THINK my images are getting to the server side, as when I return the request object, I get the following in console:
Thus, the CSRF token is getting through, and the images (I think?) are getting through. My problem from here is accessing the files with PHP and storing them via ->store();.
In the countless examples online/documentation, they typically use something along the lines of:
$path = $request->photo->store('images');
However, I don't understand the 'photo' aspect of this. What if a video or a PDF is uploaded? I basically don't understand how I am to access the different parts of the request object. Documentation on Laravel site is pretty sparse for this and only gives an example using 'photo' of which it never explains.

Figured it out.
In my uploadscontroller:
class UploadsController extends Controller
{
public function UploadFiles(Request $request){
$arr = [];
foreach($request->all() as $file){
if(is_file($file)){
$string = str_random(16);
$ext = $file->guessExtension();
$file_name = $string . '.' . $ext;
$filepath = 'uploads/' . Auth::user()->username . '/' . $file_name;
$file->storeAs(('uploads/' . Auth::user()->username), $file_name);
array_push($arr, [$file_name, $filepath]);
}
}
return $arr;
}
}

This took me a while but I finally got a working solution. I'm using Dropzone so the list of file objects is returned by getAcceptedFiles() but it should be the same concept for you. I'm also attaching the files to an existing form.
Upload:
var formElement = document.getElementById("addForm");
var formData = new FormData(formElement);
// Attach uploaded files to form submission
var files = myDZ.getAcceptedFiles(); // using Dropzone
for (var i = files.length - 1; i >= 0; i--) {
formData.append('files[]', files[i]);
}
$.ajax({
url: 'home/',
data: formData,
processData: false,
contentType: false,
timeout: 1000,
type: 'POST',
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken,
},
success: function(){
...
},
error: function (jqXHR, textStatus) {
...
}
});
Controller:
foreach($request->only('files') as $files){
foreach ($files as $file) {
if(is_file($file)) { // not sure this is needed
$fname = $file->getClientOriginalName();
$fpath = $file->store('docs'); // path to file
}
}
}
Dropzone Script:
Dropzone.autoDiscover = false;
var myDZ = new Dropzone("#my-dropzone", {
url: "/home/files",
maxFilesize: 5,
maxFiles: 5,
addRemoveLinks: true,
dictDefaultMessage: 'Drop files here or click to upload <br> (max: 5 files)',
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken
},
});

Regarding the examples found in Laravel's documentation, 'photo' is simply making use of a magic method to reference a file uploaded with a name of 'photo'. You can replace 'photo' with whatever your specific file names is/are. Specific functions capable of being called on your uploaded files can be found here.

Related

Send custom ajax data object from pseudo form (div) within form [duplicate]

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.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
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

Php ajax multiple file upload with new array

its mine upload html code ;
<div class="col-xs-12">
<label for="upload" class="btn btn-sm btn-outline green btn-block">
<i class="fa fa-upload"></i>
upload
</label><input type="file" multiple id="upload" class="hidden"/>
</div>
its file element on change method
$("#upload").change(function (event) {
var files = event.target.files;
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
});
Ajax code when click upload button..
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles', file);
});
myFormData.append('a', 1);
$.ajax({
url: 'ajax/upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
And Last of code is php code;
$myFiles=$_FILES["myFiles"];
for($i=0; $i<count($myFiles); $i++){
$target_path = "uploaded_files/";
print_r($myFiles[$i]);
echo $myFiles[$i]["tmp_name"]."\n";
$ext = explode('.',$myFiles[$i]["tmp_name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
$sonuc=move_uploaded_file($myFiles[$i], $target_path);
if(move_uploaded_file($myFiles[$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
i get this message when run the code. There was an error uploading the file, please try again! I want to upload multiple file to server with array. Why i need an array because I delete some file in array and i want to upload last result of array to server.
What is my fault ? I didn't find anything.
The $myFiles[$i] is a null object.
You are appending single file using this line of code myFormData.append('myFiles', file);. You have to use this code myFormData.append('myFiles[]', file); to send multiple file. Below is the code that i have implemented which can upload multiple files.
in your script place below code.
<script type="text/javascript">
$("#upload").change(function (event) {
var files = event.target.files;
var uploadingFile = [];
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles[]', file);
});
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
});
</script>
And in your upload php code place below code.
$target_path = "uploaded_files/";
$myFiles=$_FILES["myFiles"];
if(count($myFiles['name']) > 1){
$total = count($myFiles['name']);
for($i=0; $i<$total; $i++){
$ext = explode('.',$myFiles["name"][$i]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"][$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error multiple uploading the file, please try again! \n";
}
}
} else {
$ext = explode('.',$myFiles["name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
try this
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
$("#finalupload").uploadFile({
url: "badocumentsupload",
id: "test",
formData: {
action: 'uploadfile',
_token: tempcsrf,
baid:curaddbaid
},
fileName: "myfile",
returnType: "json",
showDelete: true,
showDone: false,
showProgress: true,
onSuccess: function (files, data, xhr) {
},
deleteCallback: function (data, pd) {
$.post("finaluploaddeletecustom", {
action: "delete_current",
row_id: data['DBID'],
filetodelete: data['uploadedfile'],
_token: tempcsrf
},
function (resp, textStatus, jqXHR) {
reloaddatatable_final();
});
pd.statusbar.hide();//You choice to hide/not.
}
});
As you are getting null object, I don't think that you files are being submitted.I think you have not used enctype="multipart/form-data" in form tag. I think if you add this to form like below, it would work.
<form action="youraction" method="post" enctype="multipart/form-data">
</form>

Ajax image upload not working as expected

I am trying to send an image via JavaScript after displaying the preview on the screen, I refuse to use Dropzone, Plupload or any JavaScript library, because I just want a simple functionality.
var finput;
var fileReader;
var fd; //formdata...
$(function(){
fileReader = new FileReader;
fileReader.onload = function(e) {
var img = document.createElement("img");
img.src = fileReader.result; //display the image on the screen...
img.height = 200;
$('#pimgbox').html(img);
//enable the image button... // $('#pimagebox').html(img);
$('#pimgbtn').removeAttr('disabled', 'disabled').removeClass('btn-alert').addClass('btn-primary');
}
});
and when you click on the submit button
$('#pimgbtn').bind('click', function(e){
//initialize the formdata...
fd = new FormData(); //initialize the formdata..
fd.append('pimgupl', finput.files[0]); //s
//alert(fd);
$('#pimgldr').css('display','block');
$(this).attr('disabled', 'disabled').removeClass('btn-primary').addClass('btn-alert')
if(fileReader.result != null){
////////////// beginning of ajax call...
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
}; //end of setting..
$.ajax(settings)
.done(function (response) {
alert(response);
resetPUplButtons();
//close modal...
$('#profimgwin').modal('hide');
})
.fail(function (jqXHR, textStatus, error) {
alert('error sending file...' + error);
resetPUplButtons();
});
/////////////////////////end of ajax calls..
}else{
alert('you havent selected an image yet..');
resetPUplButtons();
}
});
and on my Laravel usercontroller I have this method that tries to upload the image but it's refusing to work.
public function setProfilePix(Request $request){
$file = $request->file('pimgupl');
$code = Auth::user()->profile->usrcode;
$targetDir = public_path() . DS . 'userdata'.DS.'ppix';
$newname = $targetDir.DS.strtolower($code).md5($code).'_'.time() .'.jpg';
// echo $newname;
//exit;
$file->move($targetDir, $newname);
echo 'saved';
}
I keep getting this error in my output panel:
Line 418 is the ajax operation, I have tried everything but nothing seems to be working. I have also added an exception to the route in my verifyCsrfToken.php - middleware, but still it isn't working.
In your jQuery try changing settings from
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
};
to
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd,
processData: false,
contentType: false,
};

How to extract values from jquery `formData` to insert into Mysql?

My code is about submitting a multipart form, through $.ajax, which is successfully doing it & upon json_encode in submit.php , its giving me this :
{"success":"Image was submitted","formData":{"fb_link":"https:\/\/www.google.mv\/",
"show_fb":"1",
"filenames":[".\/uploads\/homepage-header-social-icons\/27.jpg"]}}
Can someone explain me, in submit.php, how can i extract values from formData, to store in mysql table ? I have tried, so many things including :
$fb_link = formData['fb_link'];
$show_fb = formData['show_fb'];
and
$arr = json_encode($data);
$fb_link=$arr['fb_link'];
and
$fb_link = REQUEST['fb_link'];
$show_fb = REQUEST['show_fb'];
but, nothing seems to work ? Any Guesses ?
Thanks
update :
JS code on parent-page is :
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form#upload_form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
//var data = new FormData($(this)[0]);
$.ajax({
url: 'jquery_upload_form_submit.php?files=files',
type: 'POST',
data: data,
//data: {data, var1:"fb_link" , var2:"show_fb"},
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'jquery_upload_form_submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
UPDATE CODE OF - submit.php :
<?php
// Here we add server side validation and better error handling :)
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = './uploads/homepage-header-social-icons/';
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename($file['name']))) {
$files[] = $uploaddir . $file['name'];
//$files = $uploaddir . $file['name'];
}
else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your image-files') : array('files' => $files);
}
else {
$data = array(
'success' => 'Image was submitted',
'formData' => $_POST
);
}
echo json_encode($data);
?>
If you're using POST method in ajax, then you can access those data in PHP.
print_r($_POST);
Form submit using ajax.
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
You can access the data on PHP
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
If you want to access file object, you need to use $_FILES
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];
This problem is different in terms that :
1. Its sending MULTIPLE files, to upload
2. Contains a SELECT
3. Contains an INPUT
So, images are serialized & sent via GET . And, rest FORM data is being sent via POST. So Solution is :
var data = new FormData($(this)[0]);
inside : function uploadFiles(event){}
And in submit.php :
print_r($_POST);
print_r($_GET);
die();
This will give you both values. Then comment these & as per the Code, make these changes :
$filename_wpath = serialize($files);
$fb_link = $_POST['fb_link'];
$show_fb = $_POST['show_fb'];
$sql = "INSERT INTO `tblbasicheader`(fldFB_image, fldFB_link, fldHideShow)
VALUES('$filename_wpath','$fb_link','$show_fb')";
mysqli_query($db_conx, $sql);
Works like Charm ! :)

ajax jquery file upload not working

I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined. I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working.The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.
My code is below:
$(document).ready(function()
{
//for checking whether the file queue contain files or not
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files
function prepareUpload(event)
{
files = event.target.files;
alert(files);
}
$("#file-form").on('submit',uploadFiles);
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
//alert(key+' '+ value);
});
$.ajax({
url: 'module/portal/filesharing/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
console.log('ERRORS: ' + data.error);
}
}
});
function submitForm(event, data)
{
// Create a jQuery object
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();//controller stops here
// sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'update.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
}
});
</script>
Html:
<form id='file-form' action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filename" ><br>
<input type="submit" id='upload' value="Upload file">
</form>
My update.php:
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = 'module/portal/filesharing/upload/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer
Maybe your problem is this one, please check this out
how to get the uploaded image path in php and ajax?

Categories