Download uploaded file with DropzoneJs - javascript

I would like to know if it is possible to download files that have been uploaded with Dropzone. For example add to the file that are shown in the dropzone a link or a button to download.
The code for upload and to show the files already uploaded:
index.php
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
$.get('upload.php', function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, "uploads/"+value.name);
});
});
thisDropzone.on("addedfile", function(file) {
var removeButton = Dropzone.createElement("<button>Remove</button>");
var _this = this;
removeButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
_this.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
thisDropzone.on("removedfile", function(file) {
if (!file.serverId) { return; }
$.post("delete-file.php?id=" + file.serverId);
});
}
};
</script>
</head>
<body>
<form action="upload.php" class="dropzone" id="my-dropzone"></form>
</body>
</html>
upload.php
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
} else {
$result = array();
$files = scandir($storeFolder);
if ( false!==$files ) {
foreach ( $files as $file ) {
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize($storeFolder.$ds.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
?>
any help will be much appreciated

Yes I found it possible by altering the dropzone.js file, not ideal for updates but only way I found that worked for me.
Add these 6 lines of code to the addedfile: function around line 539 note Ive marked the code that exists already
// the following line already exists
if (this.options.addRemoveLinks) {
/* NEW PART */
file._openLink = Dropzone.createElement("<a class=\"dz-open\" href=\"javascript:undefined;\">Open File</a>");
file._openLink.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
window.open("http://www.mywebsite.com/uploadsdirectory/"+file.name);
});
/* END OF NEW PART */
// the following lines already exist
file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
file._removeLink.addEventListener("click", function(e) {
Then you'll need to edit the CSS with a class 'dz-open', to style the button.

myDropzone.on("success", function(file) {
var a = document.createElement('a');
a.setAttribute('href',"/uploads/" + file.fullname);
a.innerHTML = "<br>download";
file.previewTemplate.appendChild(a);
});

This can be accomplished using the the example below. You will still need to tweak it to your needs.
I want to display additional information after a file uploaded.
To use the information sent back from the server, use the success
event, like this:
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, responseText) {
// Handle the responseText here. For example,
// add the text to the preview element:
file.previewTemplate.appendChild(document.createTextNode(responseText));
});
}
};

Use this in init function after ajax call. I had the same issue. Solved using this.
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr('id', "filename_" + index);
var selectFile = document.querySelector("#filename_" + index);
selectFile.addEventListener("click", function () {
window.open("http://localhost:8080/<<contextpath>>/pathtofile/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});

you can also add a empty link to your images and when your upload is ready you can fetch the image-src and set it to your link ;)
<a href="#">
<img src="" data-dz-thumbnail/>
</a>
$("img.data-dz-thumbnail").each(function() {
$(this).closest("a").attr("href", $(this).attr("src"));
$(this).closest("a").attr("target", "_blank");
});

My code is something like this.
success: function(file, rawResponse){
file.previewElement.onclick = function() {
alert(1);//do download
}
},

code is..
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr("id", "filename_" + index);
$("#filename_" + index).on("click", function(){
window.open("URL/path/folder/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});

Yes. I found a way by adding a custom preview template (adding a download button there and setting a data-file-id attribute). Then when defining the dropzone on the document ready, I searched for the last generated button element and modified the "data-file-id" attribute to save the file id.
I did the same on the 'success' event of dropzone.
After this I listened to the on click event of the download button and looked for the data-file-id attribute.
var oakDropzone = new Dropzone("#oakDropzone", {
url: "/trabajo/uploadFile",
init: function () {
var trabajoId = $("#trabajoId").val();
var getArchivosUrl = "/trabajo/getArchivosByTrabajo?trabajoId=" + trabajoId;
$("#fileLoader").show();
$.get(getArchivosUrl)
.done(function (response) {
for (var i = 0; i < response.data.length; i++) {
var file = response.data[i];
var fileData = { id: file.Id, name: file.Nombre, size: file.Tamaño, metadata: file.Metadata };
fileData.accepted = true;
oakDropzone.files.push(fileData);
oakDropzone.emit('addedfile', fileData);
oakDropzone.emit('thumbnail', fileData, 'data:' + response.data[i].Extension + ';base64,' + response.data[i].Preview);
oakDropzone.emit('complete', fileData);
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', fileData.id);
}
$("#fileLoader").hide();
$('#oakDropzone #template .dz-details .actionButtons .downloadFile').on('click', function (event) {
event.preventDefault();
var archivoId = $(this).data('file-id');
var downloadUrl = "http://localhost:11154/trabajo/downloadFile?fileId=" + archivoId;
window.open(downloadUrl, 'blank');
});
}).catch(function (response) {
displayErrorToaster(response);
});
this.on("sending", function (file, xhr, formData) {
formData.append("Id", trabajoId);
formData.append("File", file);
});
this.on("success", function (file, response) {
file.id = response.data;
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', file.id);
displaySuccessToaster(response);
});
this.on("removedfile", function (file) {
var deleteUrl = "/trabajo/RemoveFile?fileId=" + file.id;
$.post(deleteUrl)
.done(function (response) {
displaySuccessToaster(response);
}).catch(function (response) {
displayErrorToaster(response);
});
});
},
dictRemoveFileConfirmation: 'Realmente desea quitar el archivo seleccionado?',
dictDefaultMessage: '',
clickable: "#btnUploadFile",
previewTemplate: document.querySelector('#previews').innerHTML,
addRemoveLinks: false
});
This looks like the following image:
Sample Image
Hope this helps you!.

Mine looks like this, this will add "download" anchor after "remove" and it will directly download the file. ("self" is just dropzone selector)
var a = document.createElement('a');
a.setAttribute('href',existing_file.url);
a.setAttribute('rel',"nofollow");
a.setAttribute('target',"_blank");
a.setAttribute('download',existing_file.name);
a.innerHTML = "<br>download";
self.find(".dz-remove").after(a);

Related

Uploading both original and resized images with ng-file-upload

I'm trying to get my app to both save in the server the resized image and the original file.
This is what I've tried so far:
HTML:
<a ng-model="originalPic"
ngf-select="uploadphototest($file)"
ngf-resize="{width: 1170, type: 'image/jpeg'}"
ngf-resize-if="$width > 1000"
ngf-model-options="{updateOn: 'change drop paste'}"
ngf-fix-orientation="true">
Upload image
</a>
JS:
$scope.uploadphototest = function (file) {
$scope.fileext = file.name.substring(file.name.lastIndexOf('.'), file.name.length);
$scope.uniqueportrait = $scope.fairnameonly + "-" + moment().format('DD-MM-YYYY-HH-mm-ss') + $scope.fileext;
Upload.imageDimensions(file).then(function(dimensions){
if (dimensions.width < 1170){
$scope.sizeerror = true;
}else{
fileor = $scope.originalPic;
Upload.upload({
url: 'uploadtest.php',
data: {
file: file,
name: Upload.rename(file, $scope.uniqueportrait),
fileor: fileor,
}
}).then(function (resp) {
...
});
};
});
};
And my PHP:
<?php
$filename = $_FILES['file']['name'];
$destination = '/home/clients/cc5399b00bc00f15dc81742a0369c7b8/discovery/register/uploadstest/' . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
$filenameor = "ORIGINAL".$_FILES['fileor']['name'];
$destinationor = '/home/clients/cc5399b00bc00f15dc81742a0369c7b8/discovery/register/uploadstest/' . $filenameor;
move_uploaded_file( $_FILES['fileor']['tmp_name'] , $destinationor );
?>
So far is going through but only uploading the resized one, the original one seems not to pass from the model to the function, as the model comes back undefined in the console...
What am I missing?
You could use the Upload.resize service of the library. Do not use ngf-resize andgf-resize-if in your HTML but resize the file in your JS. Something like:
HTML:
<a ng-model="originalPic"
ngf-select="uploadphototest($file)"
ngf-model-options="{updateOn: 'change drop paste'}"
ngf-fix-orientation="true">
Upload image
</a>
JS
$scope.uploadphototest = function (file) {
$scope.fileext = file.name.substring(file.name.lastIndexOf('.'), file.name.length);
$scope.uniqueportrait = $scope.fairnameonly + "-" + moment().format('DD-MM-YYYY-HH-mm-ss') + $scope.fileext;
Upload.imageDimensions(file).then(function(dimensions){
if (dimensions.width < 1170){
$scope.sizeerror = true;
} else if(dimensions.width > 1000){
var resizeOptions = {
width: 1170
};
Upload.resize(file, resizeOptions).then(function(resizedFile) {
uploadFile(file, resizedFile);
});
} else {
uploadFile(file, file);
}
});
};
function uploadFile(originalFile, resizedFile) {
Upload.upload({
url: 'uploadtest.php',
data: {
file: resizedFile,
fileor: Upload.rename(file, $scope.uniqueportrait), //This returns a file
}
}).then(function (resp) {
...
});
}
Here's a fiddle of something similar: JSFiddle

PHP Javascript - cannot change selector onclick to Remove preview files

I'm doing upload multiple files(use <input type="file" multiple/>) with preview image file and can remove the image preview and filedata successfully.
but the problem is, I cannot change the selector for onclick to remove filedata.
(If I change to other selector, it will only remove the preview image but the files still be uploaded to my folder)
The selector for click to remove that work successfully is .selFile but when
I want to change selector for onclick to .selFile2 it will not remove filedata)
these are my focus line of code. (To see my Full code, Please look on bottom)
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile'
title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
..
I change from
$("body").on("click", ".selFile", removeFile);
to
$("body").on("click", ".selFile2", removeFile);
but it remove preview image only not remove filedata (it's still be uploaded to my folder)
..
And I try to change code in function removeFile(e)
from var file = $(this).data("file"); to var file = $('.selFile).data("file"); the result is It can remove only 1 filedata.
...
How could I do?
Here is my full code (2 pages)
firstpage.html (I use ajax to post form)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
cursor:pointer;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
..
upload.php page
<?php
for($i=0;$i < count($_FILES["files"]["name"]);$i++)
{
if($_FILES["files"]["name"][$i] != "")
{
$tempFile = $_FILES['files']['tmp_name'][$i];
$targetFile = "upload/". $_FILES["files"]["name"][$i];
move_uploaded_file($tempFile,$targetFile);
}
}
?>
It is because when the browser listens to the click event for a .selFile2 element, the img tag becomes the sibling of the event.target (the .selFile2).
Once you delegate the click events to the span tags, $("body").on("click", ".selFile2", removeFile);
You just need to modify your removeFile function a little bit like below.
function removeFile(e) {
var img = e.target.parentElement.querySelector("img");
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
I have just tested the code and and it is working on my end.

Is there a way not to let a blob (createObjectURL) show the image which is a GIF file but has a .jpeg extension?

Using blueimp, I'm making a file upload module and I will show an image thumbnail before people upload the image.
My code contains the following:
$('.fileupload').fileupload({
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
maxNumberOfFiles: 1,
maxFileSize: 3000000,//3MB
loadImageMaxFileSize: 3000000,//3MB
}).on('fileuploadsubmit', function (e, data) {
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('.files');
$.each(data.files, function (index, file) {
// ファイル情報を表示する
var node = $('<p/>')
.append($('<span/>').text(file.name));
// プレビューを表示する
if (!index) {
node.append('<br>');
if((/\.(jpe?g|png)$/i).test(data.files[0].name))
{
node.append('<img class= "uploaded-image" src="'
+ URL.createObjectURL(data.files[0]) + '"/><br>');
}
node.append(uploadButton.clone(true).data(data))
.append(cancelButton);
}
node.appendTo(data.context);
});
}) // .on(... code following
It works well, but if people change a GIF file extension to ".jpeg" and upload it, the blob will also work well to show the GIF and, I think it's not safe. Is there a way not let blob to show the thumbnail In this case?
When submit the file, I'm checking the file in the server side if the file is really an image file (although it has a valid extension).
(this link helped me)
The code below worked well:
if (!index) {
node.append('<br>');
if((/\.(jpe?g|png)$/i).test(data.files[0].name))
{
if (window.FileReader && window.Blob)
{
var blob = data.files[0]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
if((header == "89504e47") || (header.substr(0,6) == "ffd8ff"))
{
$("button.upload").before('<img class= "uploaded-image" src="' + URL.createObjectURL(data.files[0]) + '"/><br>');
$(".file_upload").attr("style", "height: 600px; overflow-y: auto");
}
else
{
$("button.upload").prop('disabled', true);
var error = $('<span class="text-danger"/>').text(msg[4]);
$('.files').append('<br>').append(error);
}
};
fileReader.readAsArrayBuffer(blob);
}
}
node.append(uploadButton.clone(true).data(data))
.append(cancelButton);
}

Issues in Uploading File using ajax in IE7 and IE8

I'm trying to upload a file in IE7 and IE8 browser using FileAPI library, but unfortunately it is not working. It is working in all the other browser but not in IE7, IE8 and it is my business requirement to make it work in IE7, IE8 too.
Here is my js code
jQuery(function ($){
$(document)
.on('click', '.imageLabel', function (evt){
imageUploadId = $(this).attr("id").split("_")[1];
previewImage = document.getElementById('previewHolderDiv_' + imageUploadId);
$("#imageError_" + imageUploadId).html("");
errorMessageUl = document.getElementById('imageError_' + imageUploadId);
removeImageIcon = document.getElementById('removeImage_' + imageUploadId);
})
var form = document.forms.vehicleDocumentForm;
var input = form.vehicleImage;
var uploadOpts = {
url: '/save-vehicle-document',
data: {},
name: 'vehicleImage',
activeClassName: 'upload_active'
};
var _onSelectFile = function (evt/**Event*/){
var file = FileAPI.getFiles(evt)[0];
if( file ){
_uploadFile(file, imageUploadId);
}
};
var _uploadFile = function (file){
uploadOpts.data = {"imageId" : imageUploadId};
var opts = FileAPI.extend(uploadOpts, {
files: {},
upload: function (){
form.className += ' '+uploadOpts.activeClassName;
},
complete: function (err, xhr){
//enableSellYourButtons();
form.className = (' '+form.className+' ').replace(' '+uploadOpts.activeClassName+' ', ' ');
var response = JSON.parse(xhr.responseText);
if( response.result == "fail"){
previewImage.html = "";
$("#imageError_" + imageUploadId).html("<li>" + response.message + "</li>");
} else {
$("#imageError_" + imageUploadId).html("");
$("#vehicleImageName_" + imageUploadId).attr("value", response.message);
}
}
});
opts.files[opts.name] = file;
FileAPI.upload(opts);
};
FileAPI.event.on(input, "change", _onSelectFile);
}); // ready
I'm getting an error
SCRIPT445: Object doesn't support this action
File: FileAPI.min.js, Line: 2, Column: 11608
My FileAPI version is 2.0.11
Any help would be greatly appreciated.
Thank you.
According to caniuse, the FileApi is not compatible with IE7/8.

PHP AJAX upload is not working correctly with php://input

I am trying to use the JavaScript/jQuery Ajax File Uploader by Jordan Feldstein available at https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
It is an older library but still very popular due to it's simplicity and for being so lightweight (around 100 lines) and you can attach it to a single form input filed and it simply works! You select a file as normal with the form inut filed and on selection it instantly uploads using AJAX and returns the uploaded file URL.
This makes the library good for my use where I am uploading a file inside a modal window which is also generate with AJAX and I have used this library in many similar projects.
My backend is using PHP and Laravel and that is where my issue seems to be.
My test script works but when I implement it into my Laravel app it returns this error....
ERROR: Failed to write data to 1439150550.jpg, check permissions
This error is set in my controller below when this code is not retuning a value...
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
So perhaps this part file_get_contents('php://input') does not contain my file data?
It does create the proper directory structure and even a file which is /uploads/backing/2015/08/1439150550.jpg
The 1439150550.jpg is a timestamp of when the upload took place. It create this file in the proper location however the file created has no content and is 0 bytes!
Below is my Laravel Controller action which handles the back-end upload and below that the JavaScript....
PHP Laravel Controller Method:
public function uploadBackingStageOneFile(){
// Only accept files with these extensions
$whitelist = array('ai', 'psd', 'svg', 'jpg', 'jpeg', 'png', 'gif');
$name = null;
$error = 'No file uploaded.';
$destination = '';
//DIRECTORY_SEPARATOR
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
$filename = $utc . '.jpg';
$folder = 'uploads/backing/'.date('Y') .'/'.date('m');
//if Directory does not exist, create it
if(! File::isDirectory($folder)){
File::makeDirectory($folder, 0777, true);
}
// Save Image to folder
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
if (!$result) {
Log::info("ERROR: Failed to write data to $filename, check permissions");
return "ERROR: Failed to write data to $filename, check permissions\n";
}
$url = $folder . '/' . $filename;
return Response::json(array(
'name' => $name,
'error' => $error,
'destination' => $url
));
}
JavaScript AJAX FIle Upload LIbrary
/*
// jQuery Ajax File Uploader
//
// #author: Jordan Feldstein <jfeldstein.com>
// https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
// - Ajaxifies an individual <input type="file">
// - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
// - Allows for extra parameters to be included with the file
// - onStart callback can cancel the upload by returning false
Demo HTML upload input
<input id="new-backing-stage-1-file" type="file">
Demo JavaScript to setup/init this lbrary on the upload field
$('#new-backing-stage-1-file').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
*/
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery );
My JavaScript usage of the above library:
// When Modal is shown, init the AJAX uploader library
$("#orderModal").on('shown.bs.modal', function () {
// upload new backing file
$('#new-backing-stage-1-file').ajaxfileupload({
action: 'http://timeclock.hgjghjg.com/orders/orderboards/order/uploadbackingimage',
params: {
extra: 'info'
},
onComplete: function(response) {
console.log('custom handler for file:');
console.log('got response: ');
console.log(response);
console.log(this);
//alert(JSON.stringify(response));
},
onStart: function() {
//if(weWantedTo) return false; // cancels upload
console.log('starting upload');
console.log(this);
},
onCancel: function() {
console.log('no file selected');
console.log('cancelling: ');
console.log(this);
}
});
});
The problem is like you said, file_get_contents('php://input') does not contain your file data.
jQuery.AjaxFileUpload plugin wrap file input element with a form element that contains enctype="multipart/form-data" attribute. 1
From php documentation: 2
php://input is not available with enctype="multipart/form-data".

Categories