How to redirect to file picker - onedrive

I am a freshman on skydrive. then I want to use file picker in html, and copy the demo code from Interactive Live SDK. but the running result, the open window is not direct to file picker page, just direct to my setting redirect_uri page. so what's wrong with my demo page? thanks
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/JavaScript">
<!--
/////////////////////////////
WL.init({ client_id: '$my appID', redirect_uri: 'http://www.learnyouwant.com' });
WL.ui({
name: "skydrivepicker",
element: "downloadFile_div",
mode: "open",
select: "multi",
onselected: onDownloadFileCompleted,
onerror: onDownloadFileError
});
WL.login({ "scope": "wl.skydrive wl.signin" }).then(
function(response) {
openFromSkyDrive();
},
function(response) {
log("Failed to authenticate.");
}
);
function openFromSkyDrive() {
WL.fileDialog({
mode: 'open',
select: 'single'
}).then(
function(response) {
log("The following file is being downloaded:");
log("");
var files = response.data.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
log(file.name);
WL.download({ "path": file.id + "/content" });
}
},
function(errorResponse) {
log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse));
}
);
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}
function onDownloadFileCompleted(response) {
var msg = "";
// For each folder selected...
if (response.data.folders.length > 0) {
for (folder = 0; folder < response.data.folders.length; folder++) {
// Use folder IDs to iterate through child folders and files as needed.
msg += "\n" + response.data.folders[folder].id;
}
}
// For each file selected...
if (response.data.files.length > 0) {
for (file = 0; file < response.data.files.length; file++) {
// Use file IDs to iterate through files as needed.
msg += "\n" + response.data.files[file].id;
}
}
log(msg);
};
function onDownloadFileError(responseFailed) {
log(responseFailed.error.message);
}
//-->
</script>

I found the reason. the redirect_uri must same with the filling in the app registeration.

Related

input file component is not updating, VueJS

I have some code where I update multiple files using a package.
Add / Remove seems to work if I console.log, but if I do a POST request, on server I get all files, even if I delete them.
Example: I add 3 files, I delete 2 of them and I do a POST, on server I get 3 files. (But on console.log it shows me that I have only 1 which is correct).
Also, I find this article , but I am not sure what to do in my case.
This is a short version of my code.
<div id="upload-files-on-update">
<file-upload
:multiple="true"
v-model="certifications"
input-id="certifications"
name="certifications[]"
#input-filter="inputFilter"
ref="upload">
<span class="button">Select files</span>
</file-upload>
</div>
new Vue({
el: '#upload-files-on-update',
data: function () {
return {
certifications: [],
}
},
components: {
FileUpload: VueUploadComponent
},
methods: {
updateFiles(){
let formData = new FormData();
this.certifications.forEach((file, index) => {
if (!file.status && file.blob) {
formData.append("certifications[]",
{
types: this.accept,
certifications_ids: this.certifications_ids,
}
);
this.loadingButton = true;
}
});
axios
.post("<?php echo $link;?>", formData, {
headers: {
"Content-Type": "multipart/form-data"
},
params:{
types: this.accept,
certifications_ids: this.certifications_ids,
}
})
},
inputFilter(newFile, oldFile, prevent) {
if (newFile && !oldFile) {
if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
return prevent()
}
if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
return prevent()
}
}
if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
newFile.blob = ''
let URL = window.URL || window.webkitURL
if (URL && URL.createObjectURL) {
newFile.blob = URL.createObjectURL(newFile.file)
}
newFile.pending = true;
newFile.thumb = ''
if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
newFile.thumb = newFile.blob
}
}
},
// Remove file from table
removeFile(index) {
this.certifications.splice(index, 1);
},
}
});
I found a solution for this problem.
//I catch ajax request and I make sure that is the request that I want it
var self = this;
$.ajaxSetup({
beforeSend: function (xhr,settings) {
if(settings.type != 'POST'){
return ;
}
if(settings.data.get('controller') != 'wcfm-memberships-registration'){
return ;
}
// Here I set file input as an empty array
settings.data.set('certifications[]',[]);
// Here I add my new files from a VueJS array
self.certifications.forEach((file, index) => {
settings.data.append("certifications[]", file.file);
});
}
});
});

I cannot integrate js query file in vue

i would like to use a js query code that I found on codepen in my vue project, but im not sure How to integrate it .
I simply pasted the file in my created() of my vue component but it doesn seem to work out.. the code is supposing to run a visual animation when typing chinese caractere in the input form.
this is the codepen : https://codepen.io/simeydotme/pen/CFcke
var $input = $('input');
$input.on({
"focus": function(e) {
$(".input-container").addClass("active");
},
"blur": function(e) {
$(".input-container").removeClass("active");
}
});
var previous = null;
setInterval( function() {
if( previous !== $input.val()
|| "" === $input.val()) {
getGoodCharacters( $input );
previous = $input.val();
}
}, 500);
function getGoodCharacters( $this ) {
var output = $this.val().trim();
var letters = output.split("");
var url = "https://service.goodcharacters.com/images/han/$$$.gif";
$(".error-container, .help").removeClass("show");
$(".output-container").empty();
for( letter in letters ) {
var img = letters[letter] + "";
var newurl = url.replace("$$$",img);
loadCharacter( newurl , img );
}
}
function loadCharacter( url , letter ) {
var img = new Image();
var $output = $(".output-container");
var $a = $("<a/>");
var l = $("input").val().length;
var cwidth = "120px";
if( l > 7 ) { cwidth = "70px"; }
else if( l > 6 ) { cwidth = "90px"; }
else if( l > 5 ) { cwidth = "100px"; }
$(img).load(function(){
$a.attr({
"href": url,
"title": "Good Character Chinese Symbol: "+ letter + ""
}).css("width", cwidth ).append( $(this) ).appendTo($output);
$(".help").addClass("show");
}).attr({
src: url
}).error(function(){
$(".error-container").addClass("show");
});
}
var $try = $(".tryme a").on("click", function(e) {
e.preventDefault();
$input.val( $(this).text() );
});
I also imported the jquery module in my componant
import $ from "jquery";
here is the html that i added in the template
<div class="container input-container">
<input type="text" id="input" placeholder="中文" value="中文"/>
</div>
Thanks!

Adal.js not setting props in localStorage

I'm having a problem using the adal.js library without Angular. (I'm using Vue.js.)
I have an authentication context instance, which is constructed with the following options (exact values have been changed to protect the innocent):
let config = {
tenant: '<tenant id>',
clientId: '<client id>',
redirectUri: 'http://myapplication.com/index.html',
// popUp: true,
cacheLocation: 'localStorage'
}
On my login page, I call authContext.login(), which redirects me first to https://login.microsoftonline.com/, where I log into AAD. Upon successful login, another redirect takes me back to my application, at the URI I've configured above, along with an id_token parameter in the URL. However, no token or other properties are stored by the library in local storage, just a few properties that are the result of the configuration.
On successful login, All I've got in localStorage is
{
adal.access.token.key: "",
adal.error: ""
adal.error.description: ""
adal.expiration.key: "0"
adal.idtoken: ""
adal.login.error: ""
adal.login.request: "http://myapplication.com/#/login"
adal.nonce.idtoken: "<a non-empty string>"
adal.session.state: ""
adal.state.login: "<a non-empty string>"
adal.token.keys: ""
adal.username: ""
}
So, as far as AAD is concerned, I've successfully authenticated, but the library itself seems to have no notion of what user is logged in, what tokens are associated with them, when the token expires, etc. Any advice on how to proceed would be most appreciated. Thank you in advance for reading.
Active Directory Authentication Library for JavaScript (ADAL JS) helps you to use Azure AD for handling authentication in your single page applications. This library is optimized for working together with AngularJS.
It will not save the tokens into the cache unless we code it. You can check the relative code from adal-angular.js. Here is a piece of code for your reference:
The saveTokenFromHash method will also save the tokens into cache and this function will execute after the page redirect back to the Angular app.
adal.js:
AuthenticationContext.prototype.saveTokenFromHash = function (requestInfo) {
this._logstatus('State status:' + requestInfo.stateMatch);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, '');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, '');
// Record error
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)) {
this._logstatus('Error :' + requestInfo.parameters.error);
this._logstatus('Error description:' + requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
this._saveItem(this.CONSTANTS.STORAGE.FAILED_RENEW, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, requestInfo.parameters.error);
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
this._loginInProgress = false;
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, requestInfo.parameters.errorDescription);
} else {
this._renewActive = false;
}
} else {
// It must verify the state from redirect
if (requestInfo.stateMatch) {
// record tokens to storage if exists
this._logstatus('State is right');
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.SESSION_STATE)) {
this._saveItem(this.CONSTANTS.STORAGE.SESSION_STATE, requestInfo.parameters[this.CONSTANTS.SESSION_STATE]);
}
var keys, resource;
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)) {
this._logstatus('Fragment has access token');
// default resource
this._renewActive = false;
resource = this.config.loginResource;
if (!this._hasResource(resource)) {
keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || '';
this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER);
}
if (requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) {
resource = this._getResourceFromState(requestInfo.stateResponse);
}
// save token with related resource
this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ACCESS_TOKEN]);
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._expiresIn(requestInfo.parameters[this.CONSTANTS.EXPIRES_IN]));
}
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ID_TOKEN)) {
this._loginInProgress = false;
this._user = this._createUser(requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
if (this._user && this._user.profile) {
if (this._user.profile.nonce !== this._getItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN)) {
this._user = null;
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Nonce is not same as ' + this._idTokenNonce);
} else {
this._saveItem(this.CONSTANTS.STORAGE.IDTOKEN, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
// Save idtoken as access token for app itself
resource = this.config.clientId;
if (!this._hasResource(resource)) {
keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || '';
this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER);
}
this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._user.profile.exp);
}
}
}
} else {
this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Invalid_state');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Invalid_state');
if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'State is not same as ' + requestInfo.stateResponse);
}
}
}
};
And this function will be called in this.$get like below:
// special function that exposes methods in Angular controller
// $rootScope, $window, $q, $location, $timeout are injected by Angular
this.$get = ['$rootScope', '$window', '$q', '$location', '$timeout', function ($rootScope, $window, $q, $location, $timeout) {
var locationChangeHandler = function () {
var hash = $window.location.hash;
if (_adal.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = _adal.getRequestInfo(hash);
_adal.saveTokenFromHash(requestInfo);
$window.location.hash = '';
if (requestInfo.requestType !== _adal.REQUEST_TYPE.LOGIN) {
_adal.callback = $window.parent.AuthenticationContext().callback;
}
// Return to callback if it is send from iframe
if (requestInfo.stateMatch) {
if (typeof _adal.callback === 'function') {
// Call within the same context without full page redirect keeps the callback
if (requestInfo.requestType === _adal.REQUEST_TYPE.RENEW_TOKEN) {
// Idtoken or Accestoken can be renewed
if (requestInfo.parameters['access_token']) {
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token']);
return;
} else if (requestInfo.parameters['id_token']) {
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token']);
return;
}
}
} else {
// normal full login redirect happened on the page
updateDataFromCache(_adal.config.loginResource);
if (_oauthData.userName) {
//IDtoken is added as token for the app
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
$rootScope.userInfo = _oauthData;
// redirect to login requested page
var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.START_PAGE);
if (loginStartPage) {
$location.path(loginStartPage);
}
}, 1);
$rootScope.$broadcast('adal:loginSuccess');
} else {
$rootScope.$broadcast('adal:loginFailure', _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION));
}
}
}
} else {
// No callback. App resumes after closing or moving to new page.
// Check token and username
updateDataFromCache(_adal.config.loginResource);
if (!_adal._renewActive && !_oauthData.isAuthenticated && _oauthData.userName) {
if (!_adal._getItem(_adal.CONSTANTS.STORAGE.FAILED_RENEW)) {
// Idtoken is expired or not present
_adal.acquireToken(_adal.config.loginResource, function (error, tokenOut) {
if (error) {
$rootScope.$broadcast('adal:loginFailure', 'auto renew failure');
} else {
if (tokenOut) {
_oauthData.isAuthenticated = true;
}
}
});
}
}
}
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
$rootScope.userInfo = _oauthData;
}, 1);
}
...
And here is a sample code which could save the tokens into cache for your reference:
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="node_modules\adal-angular\lib\adal.js"> </script>
<script src="config.js"> </script>
</head>
<body>
<div>
<button onclick="login()" >Login</button>
</div>
<script>
var authContext=new AuthenticationContext(config);
function login(){
authContext.login();
}
function init(configOptions){
if (configOptions) {
// redirect and logout_redirect are set to current location by default
var existingHash = window.location.hash;
var pathDefault = window.location.href;
if (existingHash) {
pathDefault = pathDefault.replace(existingHash, '');
}
configOptions.redirectUri = configOptions.redirectUri || pathDefault;
configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;
// create instance with given config
} else {
throw new Error('You must set configOptions, when calling init');
}
// loginresource is used to set authenticated status
updateDataFromCache(authContext.config.loginResource);
}
var _oauthData = { isAuthenticated: false, userName: '', loginError: '', profile: '' };
var updateDataFromCache = function (resource) {
// only cache lookup here to not interrupt with events
var token = authContext.getCachedToken(resource);
_oauthData.isAuthenticated = token !== null && token.length > 0;
var user = authContext.getCachedUser() || { userName: '' };
_oauthData.userName = user.userName;
_oauthData.profile = user.profile;
_oauthData.loginError = authContext.getLoginError();
};
init(config);
function saveTokenFromHash(){
var hash = window.location.hash;
var requestInfo = authContext.getRequestInfo(hash);
if (authContext.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = authContext.getRequestInfo(hash);
authContext.saveTokenFromHash(requestInfo);
window.location.hash = '';
if (requestInfo.requestType !== authContext.REQUEST_TYPE.LOGIN) {
authContext.callback = window.parent.AuthenticationContext().callback;
}
}
}
saveTokenFromHash();
</script>
</body>
</html>

Parse multiple pages with phantomjs

I have made a code that parses all URL-s from a page. Next, I would like to get a href from every parsed URL <div class="holder"></div> and output it to a file and sepparate with a comma.
So far I have made this code. It is able to find all the URL-s need to be parsed and collects them to a comma sepparated file called output2.txt.
var resourceWait = 300,
maxRenderWait = 10000,
url = 'URL TO PARSE HREF-s FROM';
var page = require('webpage').create(),
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };
function doRender() {
var fs = require('fs');
var path = 'output2.txt';
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
fs.write(path,page.evaluate(function() {
return $('.urlDIV').find('a')
.map(function() {
return this.href;})
.get()
.join(',');
}), 'w');
phantom.exit()
});
}
page.onResourceRequested = function (req) {
count += 1;
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(url, function (status) {
if (status !== "success") {
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
console.log(count);
doRender();
}, maxRenderWait);
}
});
Thanks in advance,
Martti

Large file upload and download ASP .NET MVC4

Can anybody give me example of code for uploading and downloading different type of files by Using Custom Control in ASP .NET MVC4 by using PlUpload Plugin. I want to save files for my task, message with unique Ids in database and want to retrieve them too. Here is my code that I tried for uploading
server side
public ActionResult UploadFiles(string id)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
and for plupload plugin code for client side for uploading file is
$("#file_attachments").pluploadQueue(
{
// General settings
runtimes: 'html5,flash,silverlight',
url: '/SideMenuBar/UploadFiles',
max_file_size: '100mb',
chunk_size: '1mb',
unique_names: true,
multipart: true,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" },
{ title: "Rar files", extensions: "rar" },
{ title: "Document files", extensions: "docx,doc,xlx,xlxs,ppt" },
],
// Flash settings
flash_swf_url: 'Script/lib/plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: 'Script/lib/plupload/js/plupload.silverlight.xap',
// PreInit events, bound before any internal events
preinit: {
Init: function (up, info) {
//alert('[Init]'+ info+ 'Features:'+ up.features);
},
UploadFile: function (up, file) {
// alert('[UploadFile]', file);
// You can override settings before the file is uploaded
up.settings.url = '/SideMenuBar/UploadFiles?id=' + file.id;
//up.settings.multipart_params = {param1: 'value1', param2: 'value2'};
}
},
// Post init events, bound after the internal events
init:
UploadComplete: function (up, files) {
// destroy the uploader and init a new one
up.destroy();
}
}
});
var uploader = $('#file_attachments').pluploadQueue();
uploader.bind('FileUploaded', function (upldr, file, object) {
if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
$(".file_upload_cancel").hide();
$(".file_upload_done").show();
}
});
uploader.bind("FilesAdded", function (up, filesToBeAdded) {
if (up.files.length > 5) {
up.files.splice(4, up.files.length - 5);
showStatus("Only 5 files max are allowed per upload. Extra files removed.", 3000, true);
return false;
}
return true;
});
$('.upload_files').click(function (e) {
e.preventDefault();
$(".file_up").show();
});
$('#new_message_form').submit(function (e) {
var uploader = $('#file_attachments').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
//uncoment next line to submit form after all files are uploaded
//$('#new_message_form')[0].submit();
}
});
uploader.start();
}
return false;
});
}
How can I resolve problem
You are using an option called "chunk", which divides your file in the size of the chunk - it's a good practice, to prevent errors.
You have determined it with the property "chunk_size". For example: you have a file of 5mb. When you upload, you'll have 5 parts of 1mb - until the upload is complete. Then, you'll have to put them together.
I recommend you to see this link to more informations about chunk and how to make it work.
Here is an example of one of my implementation - with MVC 3 - of plupload with chunk.
I'll post the javascript code and the action. I think it will be good for you to know how to implement in your case.
function installFolderFileUploader(action, id, ProfileType, intMaxFilesPermitted, Folder, maxSizeMB) {
var uploaderRuntimes = 'html5, flash, silverlight';
var uploader = new plupload.Uploader({
runtimes: uploaderRuntimes,
browse_button: 'imgBtnPhotoUpload',
url: action,
flash_swf_url: '/Scripts/Plugins/Moxie.swf',
silverlight_xap_url: '/Scripts/Plugins/Moxie.xap',
multipart_params: { 'id': id, 'ProfileType': ProfileType },
multi_selection: true,
max_file_count: '5',
chunk_size: '100KB',
filters: {
max_file_size: maxSizeMB + 'MB'
},
init: {
FileUploaded: function (Up, File, Response) {
var jsonObj = jQuery.parseJSON(Response.response);
if (jsonObj.success) {
mountFileUploadFields(jsonObj, Folder, ProfileType);
}
},
PostInit: function () {
//meow
$('#imgBtnPhotoUpload').next().css({ 'top': '0', 'width': '146px', 'height': '28px', 'cursor': 'pointer' });
},
FilesAdded: function (up, files) {
var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
if ((up.files.length + totalInPage) > parseInt(intMaxFilesPermitted)) {
jQuery.facebox({ div: "#dvMaxFilesPermitedError" });
up.splice();
up.refresh();
return false;
}
else {
if (totalInPage >= parseInt(intMaxFilesPermitted)) {
jQuery.facebox({ div: "#dvMaxFilesPermitedError" });
up.splice();
up.refresh();
return false;
}
else {
$('#dvFileList').css('margin-left', '2px');
$('#dvFileList').css('font-size', '10px');
$('#dvFileList').css('display', 'block');
plupload.each(files, function (file) {
$('#dvFileList').append('<div>');
$('#dvFileList').append('<div style="width:84%;margin-left:30px;float:left;" id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b></div>');
$('#dvFileList').append('<img class="removeFile" style="margin-top:2px;cursor:pointer;" src="/Content/images/cancel.png" id="' + file.id + '" />');
$('#dvFileList').append('</div>');
$('.removeFile').on('click', function () {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
uploader.stop();
uploader.splice();
});
});
uploader.start();
}
}
},
UploadProgress: function (up, file) {
if (file.percent == 100) {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
}
$('#' + file.id + ' b:eq(0)').html('<span> - ' + file.percent + '%</span>');
$('#' + file.id + ' b:eq(0)').append('<div id="fileUploaded" style="background-color:#0099FF;height:3px;width:' + file.percent + '%";></div>');
},
ChunkUploaded: function (up, file, info) {
var jsonObj = jQuery.parseJSON(info.response);
if (jsonObj.tempFile != "") {
uploader.settings.multipart_params.tempFile = jsonObj.tempFile;
}
else {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
if (totalInPage > 0)
$('.BeeEditFileActions').fadeIn();
var fileName = uploader.settings.multipart_params.tempFile;
removeNonUsedFiles(id, fileName, 'File');
uploader.settings.multipart_params.tempFile = '';
uploader.stop();
uploader.splice();
uploader.refresh();
jQuery.facebox({ div: "#dvAddFolderFileError" });
}
},
Error: function (up, err) {
if (err.code != '-500')
jQuery.facebox({ div: "#dvAddFolderFileError" });
},
UploadComplete: function (a, Response) {
$('.BeeEditFileActions').fadeIn();
$('#dvFileList').empty();
uploader.splice();
uploader.refresh();
}
}
});
uploader.init();
}
And the Action:
[AllowAnonymous]
[HttpPost]
public JsonResult UploadFolderFile(string id, Domain.Profile.TypeProfile ProfileType, string tempFile, string name, int? chunk, int? chunks)
{
String strTempFile = string.Empty;
String strSaveLocation = string.Empty;
try
{
var fileData = Request.Files[0];
chunk = chunk ?? 0;
String strExtension = Path.GetExtension(name).ToLower();
Models.Identity.CustomIdentity objUser = new Models.Identity.CustomIdentity(System.Web.Security.FormsAuthentication.Decrypt(id));
DB.CompanyNetworkDB objCompanyDB = new DB.CompanyNetworkDB();
Int32 intMaxFileSize = objCompanyDB.getFileInFolderMaxSize(objUser.CompanyNetworkID) * 1024 * 1024;
if (objUser != null && objUser.IsAuthenticated && fileData.ContentLength <= intMaxFileSize)
{
////Get upload file.
String strSaveLocationURL = Domain.Profile.getUploadItemsFolder(objUser.CompanyNetworkID, ProfileType, Domain.Profile.UploadType.Folder);
strSaveLocationURL += "temp/";
strSaveLocation = Server.MapPath(strSaveLocationURL);
strTempFile = string.IsNullOrEmpty(tempFile) ? DateTime.Now.Ticks.ToString() + strExtension : tempFile;
long fileSize = 0;
using (var fs = new FileStream(Path.Combine(strSaveLocation, strTempFile), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileData.InputStream.Length];
fileData.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fileSize = fs.Length;
}
if (fileSize <= intMaxFileSize)
{
if (chunk == chunks - 1)
{
return Json(new { success = true, OriginalFileName = Path.GetFileName(name), ServerFileName = strTempFile, SizeMB = fileSize });
}
else
{
return Json(new { success = true, tempFile = strTempFile });
}
}
else
{
return Json(new { success = false });
}
}
else
{
return Json(new { success = false });
}
}
catch (ArgumentOutOfRangeException)
{
System.IO.File.Delete(Path.Combine(strSaveLocation, strTempFile));
return Json(new { success = false, erro = "canceled" });
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I think it could help.