My code below works fine so long as I only load 2 multiple files. If I load 3 or more, every file after the 2nd one does not get added to my s3 bucket (although no error is shown by plupload).
Can anyone understand why?
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'https://s3.amazonaws.com/mybucket',
filters: {
max_file_size: '25mb',
prevent_duplicates: true,
multiple_queues: true
}
});
uploader.init();
uploader.bind('FilesAdded', function (up, files) {
plupload.each(files, function (file) {
var myFileName = file.name.toLowerCase();
myFileName = myFileName.replace(/[|&;$%#"<>()+,]/g, "");
var elem = $('#hfReplyGuid');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "WebService.asmx/prepareUpload",
data: "{'acl':'private','bucket':'myBucket','file':'" + folderPath + elem.val() + "_" + myFileName + "'}",
success: function (data) {
params[myFileName] = { policy: data.d[0].Policy, signature: data.d[0].Signature };
var multipart_params = {
'key': folderPath + elem.val() + "_" + myFileName,
'filename': folderPath + elem.val() + "_" + myFileName,
'AWSAccessKeyId': AWSAccessKey,
'acl': 'private',
'signature': params[myFileName]["signature"],
'policy': params[myFileName]["policy"],
'success_action_status': '201'
}
up.setOption('multipart_params', multipart_params);
uploader.start();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
I solved this by basing code on this post Upload multiple files to Amazon S3 using plupload
However I had to create the policies in the FileFiltered event, start the uploader in the FilesAdded event and then add each policy in the BeforeUpload event as below:
var multipart_params = policies[file.id];
up.setOption('multipart_params', multipart_params);
Related
JS function:
(function () {
//fix to dismiss tooltips of iOS Safari
if ('ontouchstart' in document.documentElement) {
$('body').css('cursor', 'pointer');
}
})();
function getOrderProgressBar(orderNumber) {
$('#order-status-container').hide();
$.ajax({
url: '/GetOrderProgressBar',
type: "POST",
data: {
orderNumber: orderNumber
},
success: function (data) {
if (data.Success) {
var activeStepTitle = "";
var stepsFraction = "";
$(".order-progress-bar-container").empty();
var html = '<div class="order-progress-bar" data-current-step-index="' + data.CurrentActiveStepIndex + '" data-current-step-description="' + data.CurrentActiveStepDesctiption + '">';
I am needing to get the value of the last line "data.CurrentActiveStepDescription" I have tried several different ways to put the value out but cannot get the program to recognize the function.
Any help is greatly appreciated!! Thank you
I used the Intervention image in my api. Then, I am trying to access it from my web, which is also Laravel but in different project. (I separated the web from the api due to some testing purposes for the api). But the image was successfully resized and saved to my public folder. But in my api there's an error then, when I comment the Image::make(), the error is gone. Why is that?
EDIT: Code from my api where I used Image::make()
$plant_image = $_FILES['image']['tmp_name'];
move_uploaded_file($plant_image, public_path()."\gallery\images\\".$_FILES['image']['name']);
$file_path = public_path() . "\gallery\images\\" . $_FILES['image']['name'];
$img = Image::make($file_path)->resize(216, 145);
$img->save();
Here is the code for the web
$(document).ready(function() {
$("form#addplant").submit(function() {
var form_data = new FormData($("#addplant")[0]);
$.ajax({
url: 'http://127.0.0.1/identificare_api/public/api/plants',
data: form_data,
type: "POST",
processData : false,
contentType: false,
success: function( json ) {
//console.log(json);
if (json.indexOf("error") > -1) {
var jsonparse = JSON.parse(json);
if(jsonparse.hasOwnProperty('error')){
location.reload(true);
alert("Code: " + jsonparse.error.code + "\n" + "Message: " + jsonparse.error.message);
}else{
location.reload(true);
alert("Please fill in empty fields");
}
}else{
window.location.href = "/home/"+ user_token;
alert("This item is currently under review! Please wait for admin's confirmation. Thank you!");
}
},
error: function(){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
});
I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com
There is an example on the website on how to construct child nodes from custom data:
$("#tree").dynatree({
[…]
onLazyRead: function(node){
$.ajax({
url: […],
success: function(data, textStatus){
// In this sample we assume that the server returns JSON like
// { "status": "...", "result": [ {...}, {...}, ...]}
if(data.status == "ok"){
// Convert the response to a native Dynatree JavaScipt object.
var list = data.result;
res = [];
for(var i=0, l=list.length; i<l; i++){
var e = list[i];
res.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
icon: false});
}
// PWS status OK
node.setLazyNodeStatus(DTNodeStatus_Ok);
node.addChild(res);
}else{
// Server returned an error condition: set node status accordingly
node.setLazyNodeStatus(DTNodeStatus_Error, {
tooltip: data.faultDetails,
info: data.faultString
});
}
}
});
[…]
});
But there is no mention on how to do this for the initialization of the tree. I tried the following:
initAjax: {
type: "POST",
url: "/doSomething",
data: ...
contentType: "application/json; charset=utf-8"
success: function(data, textStatus){
// In this sample we assume that the server returns JSON like
// { "status": "...", "result": [ {...}, {...}, ...]}
if(data.status == "ok"){
// Convert the response to a native Dynatree JavaScipt object.
var list = data.result;
res = [];
for(var i=0, l=list.length; i<l; i++){
var e = list[i];
res.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
icon: false});
}
// PWS status OK
node.setLazyNodeStatus(DTNodeStatus_Ok);
node.addChild(res);
}else{
// Server returned an error condition: set node status accordingly
node.setLazyNodeStatus(DTNodeStatus_Error, {
tooltip: data.faultDetails,
info: data.faultString
});
}
}
},
But then I get an error saying success doesn't work and to use some other method, but there is no documentation on how to use the other method? Can anyone help me out here? I tried using dataFilter to filter out my json string that is being returned, but that didn't work; I tried to use onPostInit and postProcess but don't know exactly what to do since there is no documentation: Do I return the data string after its been reformated, do I return the json version of the data? do I just do data = format(data)?
Any help would be greatly appreciated.
I will be having a lot of status codes and need to do different things based on the code; such as if I have code 1 it means I need to change the class of the node to have red text; or if I return code 2 it means there was an internal error and I need to add that to the node text; etc.
I have this code here:
var infiltrationResult;
while(thisOption) {
var trNode = document.createElement('tr');
var tdNode = document.createElement('td');
var hrefNode = document.createElement('a');
infPlanetID = thisOption.getAttribute('value');
var myURL = "http://www.hyperiums.com/servlet/Planetinf?securitylevel=90&newinfiltr=New+infiltration&planetid=" + PlanetID + "&infplanetid=" + infPlanetID;
GM_xmlhttpRequest({
method: 'GET',
url: myURL,
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
if (responseDetails.responseText.match(/<b>Invalid order<\/td><\/tr><tr><td><BR><center><font color=#AAAA77 face=verdana,arial size=2>The target planet is blocking all infiltrations[\s\S]<BR><BR>/im)) {
// Successful match
infiltrationResult = 'Invalid Order';
} else {
// Match attempt failed
infiltrationResult = 'Infiltration Successfully Created';
}
}
});
When I add
alert(infiltrationResult);
right after it is assigned, I correctly see the string.
However, after the function has exited, I have try the same alert and I get:
undefined
Any ideas what I'm doing wrong?
The request runs asynchronously. That's why the function takes an onload callback function in the first place. If it were synchronous, then GM_xmlhttpRequest would simply return the response details like an ordinary function.
While waiting for the request to return, the code after the call to GM_xmlhttpRequest continues running. Your script correctly identifies that infiltrationResult is undefined because the request hasn't completed yet.
If you need to do more than just assign the variable when the request comes back, then do that in the onload callback.
Try this:
var infiltrationResult;
while(thisOption) {
var trNode = document.createElement('tr');
var tdNode = document.createElement('td');
var hrefNode = document.createElement('a');
infPlanetID = thisOption.getAttribute('value');
var myURL = "http://www.hyperiums.com/servlet/Planetinf?securitylevel=90&newinfiltr=New+infiltration&planetid=" + PlanetID + "&infplanetid=" + infPlanetID;
GM_xmlhttpRequest({
method: 'GET',
url: myURL,
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
if (responseDetails.responseText.match(/<b>Invalid order<\/td><\/tr><tr><td><BR><center><font color=#AAAA77 face=verdana,arial size=2>The target planet is blocking all infiltrations[\s\S]<BR><BR>/im)) {
// Successful match
infiltrationResult = 'Invalid Order';
} else {
// Match attempt failed
infiltrationResult = 'Infiltration Successfully Created';
}
sentback(infiltrationResult);//Sent it when it loads only
}
});
function sentback(x){
alert(x);
}