I'm working on file uploads and I wanted a plugin that could let users easily update their profile pictures, or avatars, with one click. Someone recommended jQueryFileUpload by blueimp. I have the view part of it setup (a link which, when clicked, opens a filechooser dialog), but I'm having problems receiving the file data. Fiddler shows the file data being posted to the url I want, but I can't seem to find where the data of the file I selected is being stored. Using
print_r($_POST);
shows only one parameter.
My javascript is the following:
$(".hoverAction").on('click', function(e) {
$(".fileInput:first").fileupload({
url: "/user/update",
singleFileUploads: true,
formData: {
type: "avatar"
},
add: function(e, data) {
var goUpload = true;
var uploadFile = data.files[0];
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
common.notifyError('You must select an image file only');
goUpload = false;
}
if (uploadFile.size > 2000000) { // 2mb
common.notifyError('Please upload a smaller image, max size is 2 MB');
goUpload = false;
}
if (goUpload == true) {
data.submit();
}
}
});
$(".fileInput:first").click();
And my POST handler is the following:
function updateAction() {
$type = $_POST['type'];
switch($type) {
case "avatar":
print_r($_POST); // returns only the type param
break;
case "cover":
break;
default:
}
}
You should follow the documentation on https://github.com/blueimp/jQuery-File-Upload/wiki/Setup on how to build the back end. The plugin archives contain a basic PHP example which you can use as a starting point.
Related
I posted about this issue not that long ago, and I thought I had figured it out but nothing is happening.
Issue: I am trying to generate a PDF file that captures the signature of a client. Essentially they type in their name in a box and that name gets displayed in the pdf.php file along with all the other information(e.g. date, terms & conditions etc..).
I created a class that extends from FPDF and though JavaScript I am sending the name that gets filled and it gets processed through that pdf.php file and should return a "signed" pdf file.
However my pdf file is not downloading, saving or any of the options (I, D, F, S).
Below is a snippet of that section in my code.
pdf.php
$tempDir = "C:/PHP/temp/";
$thisaction = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
$answers = filter_input(INPUT_POST, 'encFormData');
$decFD = json_decode($answers);
$pdf = new WaiverFPDF();
// Pull values from array
$returnVals = array();
$returnVals['result'];
$returnVals['html'] = '';
$returnVals['errorMsg'] = '';
//the name of the person who signed the waiver
$name = $decFD->signWaiver;
$today = date('m/d/Y');
if($thisaction == 'waiverName'){
// Generate a new PDF
$pdf = new WaiverFPDF();
$pdf->AddPage()
$pdfFile = "Waiver". $name . ".pdf";
....
// Output form
$pdf->Write(8, 'I HEREBY ASSUME ALL OF THE RISKS...');
// Line Break
$pdf-> all other info...
$outFile = $tempDir . $pdfFile;
//output pdf
$pdf->Output('D', $pdfFile);
$returnVals['result'] = true;
}
else{
$returnVals['errorMsg'] = "There was an error in waiver.php";
$returnVals['result'] = false;
}
echo json_encode($returnVals);
?>
.js file (JSON)
function sendWaiver(){
var formHash = new Hash();
formHash.signWaiver = $('signWaiver').get('value');
console.log ("name being encoded");
waiverNameRequest.setOptions({
data : {
'encFormData' : JSON.encode(formHash)
}
}).send();
return true;
}
waiverNameRequest = new Request.JSON({
method : 'post',
async : false,
url : 'pdf.php',
data : {
'action' : 'waiverName',
'encFormData' : ''
},
onRequest : function() {
// $('messageDiv').set('html', 'processing...');
console.log("waiver onRequest");
},
onSuccess : function(response) {
$('messageDiv').set('html', 'PDF has been downloaded');
if (response.result == true) {
console.log('OnSuccess PDF created');
} else {
$('messageDiv').set('html', response.errorMsg);
console.log('PDF error');
}
}
});
I know my error handling is very simple, but all I am getting is success messages, but no generated pdf file... I'm not sure what i am doing wrong. I also made sure the file (when i save to a file) is writable.
class_WaiverFPDF.php
class WaiverFPDF extends FPDF
{
// Page header
function Header()
{
// Arial bold 15
$this->SetFont('Arial','B',12);
// Position XY X=20, Y=25
$this->SetXY(15,25);
// Title
$this->Cell(179,10, 'Accident Waiver ','B','C');
// Line break
$this->Ln(11);
}
// Page footer
function Footer()
{
// Position from bottom
$this->SetY(-21);
// Arial italic 8
$this->SetFont('Arial','I',8);
$this->Ln();
// Current date
$this->SetFont('Arial','I',8);
// $this->Cell(179,10,$today,0,1,'R',false);
// $today= date('m/d/Y');
$this->Cell(115,10,' Participant Name',0,0,'C');
$this->Cell(150,10,'Date',0,'C',false);
// Page number
//$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}
I have a MVC app that Im trying to use CKEditor with. One example I was looking at is here but there are many others. So far so good, but one section im still curious about, is the js that sends the selected file name back to the file upload dialog textbox.
<script type="text/javascript">
$(document).ready(function () {
$(".returnImage").click("click", function (e) {
var urlImage = $(this).attr("data-url");
window.opener.updateValue("cke_72_textInput", urlImage);
window.close();
});
});
</script>
In particular, the cke_72_textInput element. My example wasnt working initially, until I opened chrome dev tools and found the actual id of the textinput, which was in my case cke_76_textInput. Why the id change I wonder? Seems a little "fragile" to refer to a specific id like this? The above js code just takes the selected image file and returns it into the textbox of the fileupload dialog.
Is there something exposed that references this textbox element indirectly without specifying it by id (via the config for example)?
On view:
$(document).ready(function () {
CKEDITOR.replace('Text-area-name', {
filebrowserImageUploadUrl: '/Controller-name/UploadImage'
});
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here. For example:
config.language = 'de';
// config.extraPlugins = 'my_own_plugin'; // if you have any plugin
// config.uiColor = '#AADC6E';
// config.image_previewText = CKEDITOR.tools.repeat(' Hier steht dann dein guter Text. ', 8 );
// config.contentsLanguage = 'de';
config.height = 350; // 350px, specify if you want a larger height of the editor
config.linkShowAdvancedTab = false;
config.linkShowTargetTab = false;
};
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
ev.data.definition.resizable = CKEDITOR.DIALOG_RESIZE_NONE;
if (dialogName == 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('advanced');
}
if (dialogName == 'image') {
dialogDefinition.removeContents('Link');
dialogDefinition.removeContents('advanced');
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('txtBorder');
infoTab.remove('txtHSpace');
infoTab.remove('txtVSpace');
infoTab.remove('cmbAlign');
}
});
}
On Contoller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
{
if (file.ContentLength <= 0)
return null;
// here logic to upload image
// and get file path of the image
const string uploadFolder = "Assets/img/";
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(string.Format("~/{0}", uploadFolder)), fileName);
file.SaveAs(path);
var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
uploadFolder, fileName);
// passing message success/failure
const string message = "Image was saved correctly";
// since it is an ajax request it requires this string
var output = string.Format(
"<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
CKEditorFuncNum, url, message);
return Content(output);
}
I had the same problem...a little frustrating that I couldn't find any official documentation, considering this seems like a common use case.
Anyways, take a look at the quick tutorial here: http://r2d2.cc/2010/11/03/file-and-image-upload-with-asp-net-mvc2-with-ckeditor-wysiwyg-rich-text-editor/. In case the link ever breaks, here's what I did.
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase upload, string ckEditorFuncNum)
{
/*
add logic to upload and save image here
*/
var path = "~/Path/To/image.jpg"; // Logical relative path to uploaded image
var url = string.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Url.Content(path)); // URL path to uploaded image
var message = "Saved!"; // Optional
var output = string.Format("<script>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}');</script>",
CKEditorFuncNum,
url,
message);
return Content(output);
}
I've been trying to find a very basic AJAX jQuery Avatar Uploading that I can use for my "settings" page so users can upload an avatar and unfortunately I can't find any.
This is my "function" so far for uploading the avatar
function uploadAvatar(){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html("Logging in, please wait....");
dataString = $('#avatarForm').serialize();
var postURL = $('#avatarForm').attr("action");
$.ajax({
type: "POST",
url: site_url+"/libraries/ajax/image-upload.php",
data:dataString,
dataType:"json",
cache:false,
success:function(data){
if(data.err){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.err);
}else if(data.msg){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
var delay = 2000;
window.setTimeout(function(){
location.reload(true);
}, delay);
}
}
});
return false;
};
For my HTML/Input is this.
<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit" id="submit-btn" onClick="uploadAvatar();" value="Upload" />
And finally this is my PHP code (I have nothing here)
$thumb_square_size = 200;
$max_image_size = 500;
$thumb_prefix = "thumb_";
$destination_folder = './data/avatars/';
$jpeg_quality = 90; //jpeg quality
$return_json = array();
if($err==""){ $return_json['msg'] = $msg; }
else{ $return_json['err'] = $err; }
echo json_encode($return_json);
exit;
So how do I start this really. I just don't know where to start, I don't know exactly what to do.
Bulletproof is a nice PHP image upload class which encorporates common security concerns and practices, so we will use it here as it also makes the whole process much simpler and cleaner. You will want to read the approved answer on this question here (https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form) to better understand the risks of accepting file uploads from users.
The PHP below is really basic and really only handle the image upload. You would want to save the path or the file name that was generated in a database or in some kind of storage if the image is uploaded successfully.
You may also want to change the directory in which the image is uploaded to. To do this, change the parameter for ->uploadDir("uploads") to some other relative or absolute path. This value "uploads" will upload the image to the libraries/ajax/uploads directory. If the directory does not exist, bulletproof will first create it.
You will need to download bulletproof (https://github.com/samayo/bulletproof) and make sure to upload or place it in libraries/bulletproof/. When you download the class from github it will be in a ZIP archive. Extract the zip archive and rename bulletproof-master director to just plain bulletproof. Place that directory in the libraries directory.
HTML
<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
</form>
JS
$('#avatar_form').submit(function( event ){
event.preventDefault();
var formData = new FormData($(this)[0]); //use form data, not serialized string
$('#avatarDialog').fadeIn();
$('#avatarDialog').html("Logging in, please wait....");
$.ajax({
type: "POST",
url: site_url + "/libraries/ajax/image-upload.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data){
if(data.code != 200){ //response code other than 200, error
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
} else { // response code was 200, everything is OK
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
var delay = 2000;
window.setTimeout(function(){
location.reload(true);
}, delay);
}
}
});
return false;
});
PHP
//bulletproof image uploads
//https://github.com/samayo/bulletproof
require_once('../bulletproof/src/bulletproof.php');
$bulletproof = new ImageUploader\BulletProof;
//our default json response
$json = array('code' => 200, 'msg' => "Avatar uploaded!");
//if a file was submitted
if($_FILES)
{
try
{
//rename the file to some unique
//md5 hash value of current timestamp and a random number between 0 & 1000
$filename = md5(time() . rand(0, 1000));
$result = $bulletproof->fileTypes(["png", "jpeg"]) //only accept png/jpeg image types
->uploadDir("uploads") //create folder 'pics' if it does not exist.
->limitSize(["min" => 1000, "max" => 300000]) //limit image size (in bytes) .01mb - 3.0mb
->shrink(["height" => 96, "width" => 96]) //limit image dimensions
->upload($_FILES['image_file'], $filename); // upload to folder 'pics'
//maybe save the filename and other information to a database at this point
//print the json output
print_r(json_encode($json));
}
catch(Exception $e)
{
$json['code'] = 500;
$json['msg'] = $e->getMessage();
print_r(json_encode($json));
}
}
else
{
//no file was submitted
//send back a 500 error code and a error message
$json['code'] = 500;
$json['msg'] = "You must select a file";
print_r(json_encode($json));
}
Bulletproof will throw an exception if the image does not pass the validation tests. We catch the exception in the try catch block and return the error message back to the JavaScript in the JSON return.
The rest of the code is commented pretty well from the Bulletproof github page etc, but comment if anything is not clear.
I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server
I'm using the jQuery plugin, "uploadify" & what I'm trying to do is hide the upload button once the upload starts, however if they click it before selecting a file it still hides it anyway.
Here is my submit function:
$("#add_list").submit(function(){
// Set new list id
$("#filename").uploadifySettings('scriptData', { 'new_list_id': $('#new_list_id').val() });
// Hide upload button
$("#upload_button").hide();
// Trigger upload
$("#filename").uploadifyUpload();
});
Is there a way I can get the value of the filename field? I've tried..
$("#filename").val()
..but that didn't work. Always blank even when selecting a file.
Ok..... So I decided to just update a hidden form field value with the 'onSelect' event; this way when they selected a file I can update the value to state they have selected a file; then check for this value before triggering the upload. If there is a problem with the upload or the user removes the file I updated the value to a blank value whenever the 'onCancel' event is triggered.
Here is the relevant code if it helps anyone else..
'onComplete': function(event, ID, fileObj, response, data) {
if (response != 'OK') {
// Cancel upload
$("#filename").uploadifyCancel(ID);
// Show upload button
$("#upload_button").show();
// Output error message
alert(response);
} else {
// Submit secondary form on page
document.finalize.submit();
}
},
'onError': function(event,ID,fileObj,errorObj) {
// Cancel upload
$("#filename").uploadifyCancel(ID);
// Format error msg
var error_msg = errorObj.type + '. Error: ' + errorObj.info + '. File: ' + fileObj.name;
alert(error_msg);
},
'onSelect': function(event,ID,fileObj) {
// Update selected so we know they have selected a file
$("#selected").val('yes');
},
'onCancel': function(event,ID,fileObj,data) {
// Update selected so we know they have no file selected
$("#selected").val('');
}
});
$("#add_list").submit(function(){
var selected = $("#selected").val();
if (selected == 'yes') {
// Set new list id
$("#filename").uploadifySettings('scriptData', { 'new_list_id': $('#new_list_id').val() });
// Hide upload button
$("#upload_button").hide();
// Trigger upload
$("#filename").uploadifyUpload();
} else {
alert('Please select a file to upload.');
}
});
Follow this.
function submitForm()
{
var html = document.getElementById('file_uploadQueue').innerHTML;
if(html.length > 0)
{
$('#file_upload').uploadifyUpload($('.uploadifyQueueItem').last().attr('id').replace('file_upload',''));
}
else
{
alert('choose file to upload');
// or you can submit the form. If uplodify is optional for u
}
}
You could also call this php function via AJAX to find out if anything was uploaded.
( I move the uploaded files to a set of folders after uploading, so this works for me pretty well ;) )
/*
* returns the number of files in the tmp folder
* #return number
*/
public function countTmpFiles()
{
$source = "path/to/your/foler"; //here are the uploaded files
$files = scandir( $source);
$result = 0;
foreach( $files as $file )
{
if ( in_array( $file, array( ".",".." ) ) )
{
continue;
}
$result++;
}
return $result;
}