I'm trying to populate my dropzone with files I'm getting from the server. I found this post which seems to do what I want, however it seems I can only call this addCustomFile function while in the init function, and not later after I've asychronisily received my data from the server (with the list of files associated with the object I'm viewing).
Dropzone.options.imageDrop = {
url: "upload.php",
previewTemplate: previewTemplate,
params: { taskId: urlParams.get('id')},
init: function() {
this.addCustomFile = function(file, thumbnail_url , response){
this.files.push(file);
this.emit("addedfile", file);
this.emit("thumbnail", file, thumbnail_url);
this.emit("processing", file);
this.emit("success", file, response , false);
this.emit("complete", file);
}
this.addCustomFile ({ //THIS WORKS
processing: true,
accepted: true,
name: "The name",
size: 12345,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, "fine.jpg", {
status: "success"
})
}
}
let imageDropZone = $("#imageDrop").dropzone();
imageDropZone.addCustomFile ({ //THIS DOESN'T WORK - addCustomFile is not a function
processing: true,
accepted: true,
name: "The name",
size: 12345,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, "fine.jpg", {
status: "success"
})
Any thoughts on how to best modify this so I can call it in a async function after the dropzone has been created?
I was able to resolve this using promises. I had to define a variable for a promise as well as one for the data that would both be in scope across the code. Then create the promise during the init and resolve it inside my other async call. Updated code below:
var imageLoadDefer; //Variable that will get a promise
var slowLoaded; //Variable that will get loaded with data async
Dropzone.options.imageDrop = {
url: "upload.php",
previewTemplate: previewTemplate,
params: { taskId: urlParams.get('id')},
init: function() {
this.addCustomFile = function(file, thumbnail_url , response){
this.files.push(file);
this.emit("addedfile", file);
this.emit("thumbnail", file, thumbnail_url);
this.emit("processing", file);
this.emit("success", file, response , false);
this.emit("complete", file);
}
//Create the promise using jQuery
imageLoadDefer =$.Deferred();
//Important: Make sure to put this into a variable that can be used in the following function
var imDrop = this;
imageLoadDefer.always(function(){
//promise is resolved and variable is now populated
imDrop.addCustomFile ({ //THIS WORKS NOW, ASYNC
processing: true,
accepted: true,
name: slowLoaded.name,
size: slowLoaded.size,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, slowLoaded.thumbnail, {
status: "success"
});
});
}
}
let imageDropZone = $("#imageDrop").dropzone();
$.getJSON('images.json', function (data) {
slowLoaded = data;
imageLoadDefer.resolve(); //data loaded so resolve image promise
}
Related
I am using the trumbowyg editor in my project. From the documentation, I know that I can use the following code to set the image upload content of the editor.
$('#editor')
.trumbowyg({
btns: ['upload'],
plugins: {
// Add imagur parameters to upload plugin for demo purposes
upload: {
serverPath: 'https://api.imgur.com/3/image',
fileFieldName: 'image',
headers: {
'Authorization': 'Client-ID xxxxxxxxxxxx'
},
urlPropertyName: 'data.link'
}
}
});
this works fine with imgur but I want to use cloudinary server instead of imgur.
could anyone please guide what I have to do with plugins:{} when using cloudinary?
also I'm using dropzone.js with cloudinary to upload image and this is also working properly.
here is dropzone function code:
Dropzone.autoDiscover = true;
var myDropzone = new Dropzone(document.getElementById('image-upload'), {
clickable: "#image-upload #btn-add",
uploadMultiple: false,
autoProcessQueue: true,
acceptedFiles:'.jpg,.png,.jpeg,.gif',
parallelUploads: 10,
maxFilesize: 9,
maxFiles: 10,
url: 'https://api.cloudinary.com/v1_1/demo_project/image/upload',
addedfile: function(file) {
// console.log(file);
new Noty({
type: 'success',
text: "Uploading...",
timeout: false
}).show();
// myDropzone.processQueue();
},
success: function(file, response){
new Noty({
type: 'success',
text: "Uploaded!",
killer: true
}).show();
newImageArray.push({
public_id: response.public_id,
url: response.url,
secure_url: response.secure_url
});
newImageArrayJSON = JSON.stringify(newImageArray);
$imageStorage.val(newImageArrayJSON)
$("#image-upload .image").html('<img src="' + response.secure_url + '">')
$("#image-upload #btn-add").hide();
$("#image-upload #btn-remove").show();
}
});
myDropzone.on('sending', function (file, xhr, formData) {
formData.append('api_key', 112233445566778);
formData.append('timestamp', Date.now() / 1000 | 0);
formData.append('upload_preset', 'mypreset');
});
Thanks in advance!
I would advise starting with the following basic implementation which I tested and worked for me:
$('#editor').trumbowyg({
btns: ['upload'],
plugins: {
upload: {
serverPath: 'https://api.cloudinary.com/v1_1/demo_project/image/upload',
fileFieldName: 'file',
urlPropertyName: 'data.secure_url',
data: [
{name: 'api_key', value: '112233445566778'},
{name: 'timestamp', value: Date.now() / 1000 | 0},
{name: 'upload_preset', value: 'mypreset'}
],
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error.responseText);
}
}
}
});
You can log in to your Cloudinary account and modify your upload preset to restrict uploads based on different conditions, the same as you do with dropzone.js, for example to only allow uploads of specific formats etc.
I want to pass some data(a guid) to the upload method of the kendoUpload so that the particular MVC Controller action method will receive that data. Each time the upload happens, I need to pass this data (guid).
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
The field is fileId. I can call the above code block in a click event of the upload button and it works but the Kendo UI styles are not applied to the upload button at the initialization.
$("#propertyAttachmentUpload").click(
function() {
var fileId = guid();
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
});
How can I initialize the fileId without loosing the Kendo UI styles.
Note: I cannot call guid() inside upload method since the upload method calls for each uploading chunk. For all the chunks the fileId should be same for a particular file.
I've resolved this problem using a global variable and setting that variable in the click event of the upload button,
var fileGuid = '';
$(document).on('click', '#propertyAttachmentUpload', function() {
fileGuid = "";
fileGuid = guid();
})
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileGuid };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
I have to veryfiy the response of the ajax call in my sencha test.
plz advise how to do it.. below is my sample code
beforeEach(()=> {
sim = Ext.ux.ajax.SimManager.init({});
controller = Ext.create('xxxx.controller.Search');
AutoLink = Ext.create('xxxx.model.search.AutoLink', {
objectType: 'myobj'
});
});
it('Should run processResponse when doSearch executes', function() {
const callback = () => {};
sim.register({
'abc.com/myurl.aspx': {
status: 401,
responseText: JSON.stringify({
'success': true,
'data': [{
'autoLink': false, 'status': 'OK', 'objectType': 'Person',
'results': [{ 'ref': 12345, 'managedBy': '01', 'ethnicAppearance': '1', 'gender': '1', 'rules': ['Forename, surname','nickname, DOB']}],
'gridDescriptor': [{'fields': [{'name': 'surname','text': 'Surname','width': 100}],
'sortOrders': ['surname','forename1']
}]
}]
})
}
});
spyOn(controller, 'doSearch'); // internal method which calls the Ext.Ajax
spyOn(controller, 'processResponse'); // internal method which process the response
controller.doSearch(AutoLink, callback, this); // making an ajax call
setTimeout(function () {
expect(controller.processResponse).toHaveBeenCalled();
}, 1000);
});
now when run the test case processResponse gets called, which is fine, but i want to verify the ajax response.
This is how I am doing it:
$.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('Test%203')/items(" + itemId + ")/FieldValuesAsText",
method: 'GET',
headers: {
'accept': 'application/json;odata=verbose'
}
}).then(function (data) {
console.log(data);
}
I don't know if this will help you to achieve exactly what you are looking for. But I would suggest giving it a shot. Then you can go to your console and save the data object to a variable (just for debugging purposes) or just from the console itself look at the object chain and check the data which was returned by your ajax call. So in my case I would find let's say name of the employee here:- data.d.results[0].PreferredName. Then if I want to use it I can just save it in a variable. Make sure you do it in the 'then' function. Here's a sample for save the name to a var:
.then(function (data) {
empName = data.d.results[0].PreferredName;
}
I am using fine uploader for uploading file on server, For this I need to make 2 web api calls.
On button click, First web api saving value and returning result in integer, and I need to pass that integer result in header for each file while uploading.
But I am not able to pass values in headers,
code,
uploader = new qq.FineUploader({
element: $('#manual-fine-uploader1')[0],
request: {
endpoint: Url.AddEvaluationFiles,
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
},
debug: true,
callbacks: {
onSubmit: function (id, fileName) {
},
onStatusChange: function (id, oldStatus, newStatus) {
if (newStatus == "uploading") {
alert("Add header");
}
},
onUpload: function (id, name) {
alert("Onupload");
this.append("RequestId", $("#ReqId").val());
}
}
});
I am calling upload function in success block of first request,
$.ajax({
type: "POST",
url: Url.Details,
data: fileData,
async: false,
success: function (result) {
if (result == 0) {
toastr.error("Please pass user id");
} else {
$("#ReqId").val(result);
alert($("#ReqId").val());
uploader.uploadStoredFiles();
}
},
error: function (err) {
toastr.error("Not able to upload art details");
}
});
Here I want to pass RequestId header in onUpload event, but it's not working, What changes I need to make to make it happen.
The request option has a customHeaders property, that allows you to set any custom header.
Your constructor call should look something like
artistmanualuploader = new qq.FineUploader({
...
request: {
endpoint: "FoaUrl.AddEvaluationFiles",
customHeaders: {
"EvaluationRequestId": $("#CurrentEvaluationReqId").val()
}
},
...
});
This app is an image uploading tool that uploads images directly from client browser to Amazon S3 using Plupload. So far, everything is working good except this issue.
I've this code forBeforeUpload event.
init: {
BeforeUpload: function (up, file) {
$.ajax({
url: '/ServerTime.ashx',
dataType: 'text',
data: { format: "yyyy-MM-dd_HH.mm.ss.fffffff" },
type: 'POST',
cache: false
}).done(function (data) {
console.log("Before setting ImageName: " + data);
imageName = data + ".JPG";
console.log("After setting ImageName: " + imageName);
up.settings.multipart_params = {
'key': key,
'Filename': imageName,
'acl': 'public-read',
'success_action_status': '201',
'AWSAccessKeyId': accessKey,
'policy': policyDocument,
'signature': policySignature
};
});
}
}
However, I've this error when try to upload a file:
HTTP Error. Upload URL might be wrong or doesn't exist.
On Console, it is printing the expected result as follows:
Before setting ImageName: 2014-04-04_13.33.45.1155072
After setting ImageName: 2014-04-04_13.33.45.1155072.JPG
I guess there is something wrong maybe because I'm using AJAX to get time from server. On the other hand, trying the following code is working without any issue.
init: {
BeforeUpload: function (up, file) {
up.settings.multipart_params = {
'key': "This_Is_Folder_Name/This_Is_File_Name.JPG",
'Filename': "This_Is_File_Name.JPG",
'acl': 'public-read',
'success_action_status': '201',
'AWSAccessKeyId': accessKey,
'policy': policyDocument,
'signature': policySignature
};
}
}
Notice that, this time I'm using static names for Filename and key, and there is no AJAX either
I really need help with this issue. Please suggest me. What I'm doing wrong with using AJAX to get server time and use it as file name?
Thanks.
You might be able to override some of their code by doing the following:
init: {
BeforeUpload: function (up, file) {
$.ajax({
url: '/ServerTime.ashx',
dataType: 'text',
data: { format: "yyyy-MM-dd_HH.mm.ss.fffffff" },
type: 'POST',
cache: false
}).done(function (data) {
console.log("Before setting ImageName: " + data);
imageName = data + ".JPG";
console.log("After setting ImageName: " + imageName);
up.settings.multipart_params = {
'key': key,
'Filename': imageName,
'acl': 'public-read',
'success_action_status': '201',
'AWSAccessKeyId': accessKey,
'policy': policyDocument,
'signature': policySignature
};
file.status = plupload.UPLOADING;
up.trigger("UploadFile", file);
});
return false;
}
}
This would cancel their trigger, so you would have to trigger it yourself. Please note, I have not tested this.
EDIT: I'm not sure if up and file are out of scope though...
If you look in the Plupload source code you'll see this:
// Private methods
function uploadNext() {
var file, count = 0, i;
if (this.state == plupload.STARTED) {
// Find first QUEUED file
for (i = 0; i < files.length; i++) {
if (!file && files[i].status == plupload.QUEUED) {
file = files[i];
if (this.trigger("BeforeUpload", file)) {
file.status = plupload.UPLOADING;
this.trigger("UploadFile", file);
}
} else {
count++;
}
}
// All files are DONE or FAILED
if (count == files.length) {
if (this.state !== plupload.STOPPED) {
this.state = plupload.STOPPED;
this.trigger("StateChanged");
}
this.trigger("UploadComplete", files);
}
}
}
The line that says if (this.trigger("BeforeUpload", file)) { will determine whether the return of the trigger call is truthy or falsy. If truthy, it will next trigger "UploadFile". What that means is that the uploading of the file does not wait for asynchronous code to execute in your BeforeUpload function. As soon as that function returns, the upload can begin. Any async ajax call you make inside your BeforeUpload function will resolve after "UploadFile" is triggered.