Uploadify and flash issue uploading to remote server - javascript

I'm trying to use uploadify to upload images to a remote server. I've have done everything I can think of for the cross scripting issue or whatever.
Here is what i've done.
scriptAccess to 'Always' in the uploadify function.
I have a crossdomain.xml on my ww2 server with uploadify.swf in the root as well.
I have uploaded my javascript jquery lib file to the remote ww2 server and put it in the header
I put the jquery.uploadify.js and the swfobject.js in the root directory as well.
If I try to click the X to cancel a file I get the error: Error calling method on NPObject
Or uploads don't work either.
If anyone can help with this that would be great. If there are any other good flash based or non flash based multi uploaders that will do remote files with no issue please let me know.
Thanks

I managed to figure it out on my own. I will answer it just incase someone else might have this issue because there is very little help even on the authors site for it.
I decided to leave the Flash file on the same server(Web server) because it didnt seem to work putting it on the media server with the javscript files. The js wouldn't work.
So my main server has the uploadify folder still on the server and I only put the php files(uploader.php) I needed to process my images on the media server AND the crossdomain.xml in the root of that server.
Then told uploadify in the parameter settings to point to my uploader.php script on that server.
Everything worked like a charm after that. I took quite a while to figure it out and get passed the errors. Now I can load balance my media.
Hope this helps someone else. Uploadify is a really nice multi file uploader.

You need to change code in your uploadify.js:
/* Original code */
uploadifyCancel:function(ID) {
jQuery(this).each(function() {
document.getElementById(jQuery(this).attr('id') + 'Uploader').cancelFileUpload(ID, true, true, false);
});
},
/*New code */
uploadifyCancel:function(ID){
jQuery(this).each(function(){
document.getElementById(jQuery(this).attr("id")+"Uploader").cancelFileUpload(ID,true,false)
});
},
/*Original code */
jQuery(this).bind("uploadifyComplete", {
'action': settings.onComplete
}, function(event, ID, fileObj, response, data) {
if (event.data.action(event, ID, fileObj, unescape(response), data) !== false) {
jQuery("#" + jQuery(this).attr('id') + ID).find('.percentage').text(' - Completed');
if (settings.removeCompleted) {
jQuery("#" + jQuery(event.target).attr('id') + ID).fadeOut(250,function() {
jQuery(this).remove()
});
}
jQuery("#" + jQuery(event.target).attr('id') + ID).addClass('completed');
}
});
/* New code */
jQuery(this).bind("uploadifyProgress", {
'action': settings.onProgress,
'toDisplay': settings.displayData
}, function(event, ID, fileObj, data) {
if (event.data.action(event, ID, fileObj, data) !== false) {
jQuery("#" + jQuery(this).attr('id') + ID + "ProgressBar").animate({
'width': data.percentage + '%'
},250,function() {
if (data.percentage == 100) {
jQuery(this).closest('.uploadifyProgress').fadeOut(250,function() {
jQuery(this).remove()
});
}
});
if (event.data.toDisplay == 'percentage') displayData = ' - ' + data.percentage + '%';
if (event.data.toDisplay == 'speed') displayData = ' - ' + data.speed + 'KB/s';
if (event.data.toDisplay == null) displayData = ' ';
jQuery("#" + jQuery(this).attr('id') + ID).find('.percentage').text(displayData);
}
});

Related

Best way to handle ajax call with port in MVC

I can't find any better solution in Google.
I have an MVC application.
When I use Visual studio the URL is
http://localhost:12345/NewApp - This works
When I deploy this to my local webserver the URL is
http://win2k12/NewApp - This works
I have a port forward on my router to port 8878 to point to the win2k12 server. I have a domain name (e.g. http://mydomain.uk) which is set to point to my actual IP xxx.xxx.xxx.xxx address. so when I want to access my MVC app externally I use this url
http://mydomain.uk:8878/NewApp - this works but only for the first level. When I call an Action through ajax like this
From the image above, the baseUrl only returns http://mydomain.uk/NewApp (without the port) which cause an error. My current workaround is to hardcode the port which is not Ideal.
I used baseUrl because If I don't the Virtual Directory doesn't get recognize. I'm sure this is just a workaround and I'm just wondering if there is a proper way of doing it.
<script>
$(document).ready(function () {
var baseUrl = '#HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)#Url.Content("~/")';
$("a").click(function (e) {
if ($(this).attr("action") == "Edit") {
$("#dlgCode").empty()
.load(baseUrl + "/Codes/Edit?id=" + $(this).attr("code_id") + "&timestamp=" + new Date().getTime());
setTimeout(function () {
$("#dlgCode").css("display", "");
$("#dlgCode").dialog({
width: "25%",
maxWidth: "768px",
title: "Edit Code"
});
}, 1000);
} else if ($(this).attr("action") == "Delete") {
$("#dlgCode").empty()
.load(baseUrl + "/Codes/Delete?id=" + $(this).attr("code_id") + "&timestamp=" + new Date().getTime());
setTimeout(function () {
$("#dlgCode").css("display", "");
$("#dlgCode").dialog({
width: "25%",
maxWidth: "768px",
title: "Delete Code"
});
}, 1000);
} else if ($(this).attr("action") == "Add") {
$("#dlgCode").empty()
.load(baseUrl + "/Codes/Add?id=" + $(this).attr("group_id") + "&timestamp=" + new Date().getTime());
setTimeout(function () {
$("#dlgCode").css("display", "");
$("#dlgCode").dialog({
width: "25%",
maxWidth: "768px",
title: "Add Code"
});
}, 1000);
}
else if ($(this).attr("action") == "Cancel") {
$("#dlgCode").dialog('close');
}
//console.log($("#dlgCode").html());
//alert($(this).attr("code_id"));
});
});
UPDATE:
I tried outputting the port from the view and re-deploy and access it externally but the port that gets recognize was 80.
alert('#HttpContext.Current.Request.Url.Port');

jquery.fn not works on server, it works on local

I wrote below function in javascript file.
Previously, below function works on my server and local, but today it works on my local only. Suddenly it stops working on server. i checked the code there is no any change. I don't understand why this happens.?
jQuery.fn.guideWidget = function(e) {
alert("guideWdget");
},
jQuery.fn.loading = function() {
this.prepend("<div class='fnLoading' style='height:" + this.height() + "px;width:" + this.width() + "px'><div class='ajaxOverlayInvis' style='display:block'></div><div class='ajaxOverlay' style='display:block;position:absolute'><div class='loadingimage' style='display:block'></div></div></div>")
},
jQuery.fn.loadingDone = function() {
this.find("div.fnLoading").first().remove()
}
Is there any alternate way to write above function?
What am i doing wrong in above function please suggest me.

How to change settings with Uploadify after control has already been created

I initialize Uploadify using the following code:
$('#file1').uploadifive({
'buttonClass': 'upload-btn',
'uploadScript': '/Upload/',
'fileObjName': 'files',
'fileType': 'text/xml',
'formData': { 'uploadType': 'Crew' },
'onUploadComplete': function(file, data) {
var results = $.parseJSON(data);
if (results.error) {
var info = file.queueItem.find('span.fileinfo');
if (info) info.text(' - ' + results.error);
return;
}
window.location.href = '#Url.Content("~/Upload/Checkdata/")' + results.id;
}
});
This works, however I need to modify the formData property when a radio checkbox changes. So, I've tried this:
$('input[name=UploadType]:radio').change(function () {
$('#file1').uploadifive({ 'formData': this.value });
});
However, when that code runs, it breaks the Uploadify control (it now no longer uploads anywhere). I'm guessing because it completely re-initializes the control with all new settings.
How can I update just this one setting? I've read the Uploadify docs and none of them say anything about updating settings; just initializing and calling methods. Thanks!
I've figured out one solution, but not sure if it's the right way to do things (i.e., it might break in future versions of Uploadify).
Basically, it appears you can keep a reference to your configuration around, and update that object at any time:
var uploadifySettings = {
'buttonClass': 'upload-btn',
'uploadScript': '/Upload/',
'fileObjName': 'files',
'fileType': 'text/xml',
'formData': { 'uploadType': 'Crew' },
'onUploadComplete': function(file, data) {
var results = $.parseJSON(data);
if (results.error) {
var info = file.queueItem.find('span.fileinfo');
if (info) info.text(' - ' + results.error);
return;
}
window.location.href = '#Url.Content("~/Upload/Checkdata/")' + results.id;
}
}
$('input[name=UploadType]:radio').change(function () {
uploadifySettings.formData.uploadType = this.value;
});
$('#file1').uploadifive(uploadifySettings);

Jquery File Upload always fails with File Upload Aborted

I'm trying to get Blueimp's Jquery File Upload plugin working on my website, but for the life of me can't get it to upload files. I've been working on this all day and am stuck. It will upload the file and submit it to the UploadHandler class, but when it's trying to complete the handle_file_upload function it gets to:
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
but that always returns 0. I cannot figure out why the file won't upload. The full response I get back is:
{"files":[
{"name":"1397489968-32",
"size":0,
"type":"multipart\/form-data; boundary=----WebKitFormBoundaryrmi4L2ouOmB4UTVm",
"error":"File upload aborted",
"deleteUrl":"http:\/\/onceridden.demomycms.co.uk\/eshop\/library\/ajax\/?file=1397489968-32",
"deleteType":"DELETE"}
]}
ajax.file-upload.php only instantiates UploadHandler, nothing else.
If you'd like to see the full code you for UploadHandler you can download it from github, it's too big for me to post on here.
Can someone please tell me why the files won't upload? Yes I've done the basics such as checking the folder is CHMOD 777. I've tried this with various files of different types (they must be images to work, limited to jpg, png or gif) and sizes; all produce the same result.
As requested this is the JS file:
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '/eshop/library/ajax/ajax.file-upload.php',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#register-photo').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#register-files');
$.each(data.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($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#register-progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index, file) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
It's pretty much the default file you get with the plugin with just the ID's changed to match my form.
Update
After much playing around and testing I have found out that the problem occurs when you change the name of the input from files to anything else. Why I have no idea. This is obviously an issue if you want to have it running on more than one input on a page...
I created a very simple version of the interface myself, and that does allow me to change the file name, so it must be something to do with the example they use. I would like to be able to use preview images and the such (something I couldn't figure out in my simple test) so I need to solve this issue.
This is in case anyone else ever gets stuck on this problem as well. The issue is caused by the paramName option, which if not set takes it's value from the input name. It's not set by default, so when changing the input name I was also changing paramName, meaning it no longer matched the variable coming back from the UploadHandler class.
The solution is to add paramName: 'files[]' as an option.
I was facing same issue(action aborted) and have different answer.
The folder/directory where I was uploading file did not have permission to upload file.
on Linux server you can run following command
chmod 777 files
When I gave permission to this directory, I did not get this error, and could upload file successfully.
I am running a centOS 6.9. chmod 0755 /server/php/files (rather than 777) and I changed the ownership (chown) over to apache. Ta-Da!

phonegap - cross platform way of getting default music folders on smartphones

im trying to get the default music folders for all phonegap supported platforms. basically i can download and save file on the sdcard using the function below. but i want to add code to detect platform and give me default music folders for platform so as i can save mp3 file there.
function downloadFile(remoteloc,new_name,userid,mid,errorbox,origname)
{
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html","");
var fileTransfer = new FileTransfer();
fileEntry.remove();
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"progress progress-danger progress-striped\"><div id='id_p' class=\"bar\" style=\"width: 5%\"></div></div>");
fileTransfer.onprogress = function(progressEvent)
{
if (progressEvent.lengthComputable) {
$('#id_p').css('width',Math.ceil((progressEvent.loaded / progressEvent.total)*100)+"%");
} else {
}
}
fileTransfer.download(
remoteloc,
sPath + new_name,
function(theFile) {
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"alert alert-info fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Download Complete. Added to Media Player</div>"
+"<div>Play Song</div>"+"<br/>"+theFile.toURI());
//update the database field to show file has been transfered
if (!isOnline())
{
$('#error_box').html("<div class=\"alert alert-error fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Sorry but you seem to be offline.</div>");
return;
}
var request={'controller':'music','action':'updatedownload','userid':userid,'mid':mid};
queryAPI(request,function (d){
//check result and set local storage variables
if (d.success>0)
{
} else
{
}
localStorage.removeItem('resume');
window.key=false;
//setTimeout(function () {$('#'+errorbox).html("<div>"+origname+"</div>");},3000);
});
},
function(error) {
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"alert alert-error fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Download Error! Error code:"+error.code+"</div>");
}
);
},
fail);
},
fail);
}
Because of major platform differences, there isn't a "one time getDirectory call" solution to do this.
The best way to handle this is to do a check for the platform you're currently running and write the file based on that.
var platform = device.platform;
switch(platform)
{
case 'iPhone':
//save to the app document folder
break;
case 'Android':
//save to <external_storage_root>/Music
break;
case 'BlackBerry':
//Save to /SDCard/BlackBerry
break;
}
Be sure to check official documentation for the right file path's etc.
Also take note that while /var/root/Media/iTunes_Control/Music is sometimes mentioned as the default folder for music on iOS, it's managed by iTunes so it can be modified at any time and is only useful for temporary storage if it can be accessed at all. Using the documents folder is the prefered method.

Categories