Upload Image using ajaxupload - php

I am using Ajax Upload for file upload via ajax and php.
At js file i wrote following line of code:
$(document).ready(function() {
if ($('#uploadExists').length) {
var btnUpload = $('#uploadExists');
var u = new AjaxUpload(btnUpload, {
action: '/upload',
name: 'fname',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
//Bad file
return false;
}
},
onComplete: function(file, response){
if (! (/(\.jpg|\.png|\.jpeg|\.gif)/.test(response))) {
//Bad file
console.log(response);
return false;
} else {
console.log(response);
}
}
});
}
});
At /upload url what should I do?
I am writing things in PHP.

At /upload (for instance /upload/index.php) you receive the file via the $_POST variable. Try doing var_dump($_POST) to see what the filename is. Then you can use http://php.net/manual/en/function.move-uploaded-file.php to move the file as you would like. This script will be sent 1 file at a time from the multi-file upload, so you handle the upload as if you were handling a single upload via a standard html form.

Related

Problem with uploading some files using Blueimp upload + cropper.js

I have a system where users can send some photos to the server, and the client receive it to make polaroid versions of them.
The user has the option to crop them or not.
I used Blueimp (https://github.com/blueimp/jQuery-File-Upload) to upload the images and cropper.js (https://fengyuanchen.github.io/cropperjs/) to crop them.
But some users are complaining that some files is not uploading, but no error is shown.
Isn't the extension, isn't the size... I don't know what could be the problem...
In this file (jquery.fileupload-ui.js) I found a line of code that, if I remove it, it works, but I can't see the file's thumbnails. But the file is uploaded. Is the last line before the always function.
add: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var $this = $(this),
that = $this.data('blueimp-fileupload') ||
$this.data('fileupload'),
options = that.options;
data.context = that._renderUpload(data.files)
.data('data', data)
.addClass('processing');
options.filesContainer[
options.prependFiles ? 'prepend' : 'append'
](data.context);
that._forceReflow(data.context);
that._transition(data.context);
data.process(function () {
// return $this.fileupload('process', data);
}).always(function () {
data.context.each(function (index) {
$(this).find('.size').text(
that._formatFileSize(data.files[index].size)
);
}).removeClass('processing');
that._renderPreviews(data);
}).done(function () {
data.context.find('.start').prop('disabled', false);
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false) {
data.submit();
}
}).fail(function () {
if (data.files.error) {
data.context.each(function (index) {
var error = data.files[index].error;
if (error) {
$(this).find('.error').text(error);
}
});
}
});

Copy a multiple file from client system to server

I don't have any idea to copy a file from client system to server.
Short Description
I am using upload folder dialog box to upload a multiple file from particular path.
XML file is mandatory, because i need to extract some information to process
While upload event i read all the information i need to process
$("#myInput").change(function() {
var names = [];
var formData = new FormData();
for (var i = 0; i < $(this).get(0).files.length; ++i)
{
var F_name= $(this).get(0).files[i].name;
var extension = F_name.replace(/^.*\./, '');
if(extension != "xml" && extension != "db"){
formData.append('userfiles[]', $(this).get(0).files[i], F_name);
}
else if(extension == "xml"){
//Gathering info
}} });
User interface fields are filled automatically after this process and user have to fill some more fields. While user click process button in server side i create folder and some new XML files too. Everything is fine except , copy a file from client to server.
//Jquery
$("#process_but" ).click(function() {
$.ajax({
type: "POST",
url: "Asset/PHP/function.php",
data: {action: "action1", DOI:doi, TLA:tla, STITLE:S_Title, SHEAD:S_Head, SLINK:S_Link, LTYPE:link_type, DESC:description, ATITLE:Art_title, JTitle:JOU_title, ANAME:Author_name, FSHARE:Fig_share, FNAMES:filenames, FCOUNT:filecount},
success: function(response) {
if(response == 1)
{alert("success");}
else
{alert("Something goes wrong.....");}
},
error: function() {
alert("Error");
}
});
});
//php
<?php
session_start();
$action = $_POST['action'];
if($action == "action1")
{
//what i have to do
}
?>

exit from parent function according to ajax success callback return value

//this function will upload file through ajax
add: function (e, data) {
//before upload file check server has that file already uploaded
$.ajax(
{
type: "POST",
dataType:'json',
url:"../admin/cgi/file_check.php",
async:false,
data:{
filename : upload_filename,
docname : upload_docname,
userid : upload_userid,
},
success:function(data)
{
//check file alreay exists
if(data['doc_name'] == 'invalid')
{
// if file alreay exists want to stop upload process
//exit from main funtion
}
},
error:function(request,errorType,errorMessage)
{
alert ('error - '+errorType+'with message - '+errorMessage);
}
});
//file uploading code
}
add: function (e, data) {} - main function upload file through ajax
before upload check server has that file already uploaded through ajax request
if file alreay exists ajax success call back return the value data['doc_name'] = 'invalid'
if file alredy exists if(data['doc_name'] == 'invalid') i want to stop uploading proccess (want to exit from main uploading function)
You can try this: If your ajax returns invalid then display error message otherwise upload file.
success:function(data)
{
//check file alreay exists
if(data['doc_name'] != 'invalid')
{
//file uploading code
}
else
{
// Display your error message.
}
},

fineUploader deleting a file

I use Fine Uploader Version: 5.0.8
1) I choose file 1.png
2) PHP script renames and upload with a new name fdba4551.png
3) I want to delete the file but not know how to pass parameters unlink($UploadDir.$_POST['??????????']);
I can not delete the file fdba4551.png
my PHP
if($method == 'POST')
{
if(move_uploaded_file($TempName, $PatchNewFile))//$PatchNewFile = uploads/fdba4551.png
{
$return = array('success'=>true,'uuid'=>$uuid,'uploadName'=>$NewFile);//$NewFile = fdba4551.png
echo json_encode($return);
}
}
elseif($method == 'DELETE')
{
unlink($UploadDir.$_POST['??????????']);//?????????????
}
my java script
<script type="text/javascript">
$(document).ready(function()
{
$('#upl').fineUploader({
debug:true,
deleteFile:{
enabled:true,method:'POST',endpoint:'upload/'
},
request:{
endpoint:'upload/'
},
callbacks:{
onComplete:function(id, name, response)
{
$('#file').append('<input type="hidden" name="load_file[]" value="'+response.uploadName+'" id="'+id+'">');
},
onDelete:function(id)
{
$('#file #'+id).remove();
}
},
validation:{allowedExtensions:['jpeg','jpg','png','gif'],acceptFiles:'image/jpeg,image/png,image/gif',itemLimit:10,sizeLimit:5*1024*1024}
});
});
</script>
As described in the delete file endpoint handler section of the docs:
Handle the POST or DELETE at your specified endpoint
Locate the file based on the file UUID included in the path of the request.
Delete the file.

jQuery-File-Upload used for UI only?

I would like to upload multiple files. The use case is: users on my website can upload multiple photographs.
Right now I am just using
<input type="file" name="myfiles" multiple="multiple">
This works well, but I want more. I'd like a nice interface showing the user what is uploaded AND for it to be more clear about which files are being uploaded.
https://github.com/blueimp/jQuery-File-Upload
So this blueimp jquery file upload script has beautiful UI and is just what I'm looking for. However there are a few issues:
1) I would like to submit the form to a php file which will DECIDE if the files get uploaded or not.
2) My form has many (many..) other fields. I would like this to submit via plain old post submit button along with the rest of my form. Is this possible?
If not, can someone recommend a better option?
Thanks!
All of the above is possible with the blueimp file upload plugin.
1) Decide if files get uploaded or not
Use the add: option in the plugin to make a separate ajax call to the server with the filenames added, and use the response to filter the list of files to be uploaded.
2) Add other data from the form to the upload
Use the formData: option in the plugin to add the other fields in a form to be passed to the server upon submit.
So something like the following:
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
loadImageMaxFileSize: 15000000, // 15MB
formData: $("#myForm").serializeArray()
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.ajax(
url: "/checkfiles",
data: { files: data.files },
success: function(result) {
// assume server passes back list of accepted files
$.each(result.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append(file.error);
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
});
}).on('fileuploadfail', function (e, data) {
$.each(data.result.files, function (index, file) {
var error = $('<span/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
});
});
});

Categories