I have a session issue, where my handler is not reading the session values. This ONLY occurs on our server. When I run local, it works fine. I'm also calling IRequiresSessionState, so that shouldn't be an issue either.
I'm able to see the session state is still working up until I call my ashx file. Inside this file however, the session is lost, according to my trace.
Here's my javascript code I use to call my handler:
$(document).ready(function () {
$("#<%=btnAdd.ClientID%>").uploadify({
'uploader': '../Scripts/Uploadify/uploadify.swf',
'script': '../Handlers/file1.ashx?mode=schedule',
'cancelImg': '../Images/cancel.png',
'wmode': 'transparent',
'hideButton': true,
'fileExt': '*.XML;*.xml;*.CIF;*.cif;*.zip;*.ZIP',
'fileDesc': 'Schedule Files',
'onComplete': function (event, queueID, fileObj, response, data) {
$('#pnlOverlayFrame').show();
document.getElementById("<%=hdnFilePath.ClientID%>").value = response;
},
'onAllComplete': function (event, queueID, fileObj, response, data) {
$get('<%= hdnDirty.ClientID %>').value = '0';
// document.getElementById('<%= btnConfirm.ClientID %>').click();
document.getElementById('<%= btnUploadFiles.ClientID %>').click();
}
,
'multi': true,
'expressInstall': '../Scripts/Uploadify/expressInstall.swf'
});
Below is my handler .cs file code
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
if (context.Session != null && context.Session["CurrentDirectory"] != null)
{
StorageRoot = context.Server.MapPath(context.Session["CurrentDirectory"].ToString());
}
else
{
//string DirectoryName = "OP1" + "_" + DateTime.Now.ToString().Replace('/', '_').Replace(':', '_').Replace(' ', '_') + Guid.NewGuid().ToString();
string DirectoryName = "OP1" + "_" + String.Format("{0:yyyyMdHHmmss}", DateTime.Now) + Guid.NewGuid().ToString();
//DirectoryName = DirectoryName.Remove(DirectoryName.Length - 3, 3);
HttpContext.Current.Session.Add("CurrentDirectory", DirectoryName);
//context.Session["CurrentDirectory"] = DirectoryName;
StorageRoot = context.Server.MapPath(DirectoryName);
}
string filename = postedFile.FileName;
if (!Directory.Exists(StorageRoot))
Directory.CreateDirectory(StorageRoot);
postedFile.SaveAs(StorageRoot + #"\" + filename);
context.Response.Write(StorageRoot);
context.Response.StatusCode = 200;
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}
Every time it goes in else part and create new folder as per code.
Please advice
I got the alternate way of handling session in ASJX file
i have pass session in 'scriptData': { 'SessionData': currentDirectory }, tag in to uploadify function and get this data in term of Form
JavascriptCode
var currentDirectory = "";
$(document).ready(function () {
$("#<%=btnAdd.ClientID%>").uploadify({
'uploader': '../Scripts/Uploadify/uploadify.swf',
'script': '../Handlers/file1.ashx?mode=schedule',
'scriptData': { 'SessionData': currentDirectory },
'cancelImg': '../Images/cancel.png',
'wmode': 'transparent',
'hideButton': true,
'fileExt': '*.XML;*.xml;*.CIF;*.cif;*.zip;*.ZIP',
'fileDesc': 'Schedule Files',
'onComplete': function (event, queueID, fileObj, response, data) {
$('#pnlOverlayFrame').show();
document.getElementById("<%=hdnFilePath.ClientID%>").value = response;
currentDirectory = response;
$("#<%=btnAdd.ClientID%>").uploadifySettings('scriptData', { 'SessionData': currentDirectory });
},
'onAllComplete': function (event, queueID, fileObj, response, data) {
$get('<%= hdnDirty.ClientID %>').value = '0';
// document.getElementById('<%= btnConfirm.ClientID %>').click();
document.getElementById('<%= btnUploadFiles.ClientID %>').click();
currentDirectory = "";
}
,
'multi': true,
'expressInstall': '../Scripts/Uploadify/expressInstall.swf'
});
we have set session data in onComplete event with use of below line
$("#<%=btnAdd.ClientID%>").uploadifySettings('scriptData', { 'SessionData': currentDirectory });
and get data in c# like below
string sessionValue = Convert.ToString(context.Request.Form["SessionData"])
Related
I have generated a PDF invoice using the file plugin. Now I want to open the file in the app. I tried inAppBrowser, but its giving an empty page. I tried fileopener, its neither giving a success or failed message. How do I specify the path to my file . please help!!
In app Browser Method
var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
cdr=dir;
alert("cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log(" write success");
};
console.log("writing to file");
writer.write( pdfOutput );
},function () {
console.log("ERROR SAVEFILE");
});
});
});
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
alert("open file");
dir.getFile("test.pdf", {create:false}, function(fileEntry) { //EXISTS
alert("native url "+cdr.toNativeURL());
var url =cdr.toNativeURL() + "test.pdf";
alert(url);
window.open(url, '_blank');
}, function() { //NOT EXISTS
alert("no file found");
});
});
}
Fileopener Method
var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory , function(dir) {
cdr=dir;
console.log(" vidhya cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log("vidhya write success");
openFile(cdr);
};
console.log("vidhya writing to file");
writer.write( pdfOutput );
},function () {
console.log("vidhya ERROR SAVEFILE");
});
});
});
function openFile(cdr) {
var fs;
function fsSuccess(fileSystem)
{
fs = fileSystem;
console.log("vidhya "+fs);
}
function fsFail(event)
{
console.log(event.target.error.code);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsFail);
console.log("vidhya opening file " +cdr.toNativeURL());
cordova.plugins.fileOpener2.open(
fs.root.toURL() +'test.pdf',
"application/pdf", //mimetype
{
error: function(e) {
alert("Error Opening the File.Unsupported document format.");
},
success: function() {
// success callback handler
alert("success");
}
}
);
}
My file is getting saved in /internal storage/Android/Data/app_folder/files/test.pdf
This is how i made it work in my hybrid mobile app:
var cdr;
sessionStorage.platform = device.platform;
var fileTransfer = new FileTransfer();
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}
function onError(e) {
navigator.notification.alert("Error : Downloading Failed");
};
function onFileSystemSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("Cordova", {
create: true,
exclusive: false
}, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
dir.getDirectory("My_App", {
create: true,
exclusive: false
}, onGetDirectorySuccess1, onGetDirectoryFail);
};
function onGetDirectorySuccess1(dir) {
cdr = dir;
dir.getFile(filename, {
create: true,
exclusive: false
}, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
var documentUrl = "http://myserverurl.com/test.pdf";
var uri = documentUrl;
fileTransfer.download(uri, cdr.nativeURL + docFileNameToView,
function(entry) {
openFile();
},
function(error) {
navigator.notification.alert("Error");
},
false
);
};
function openFile() {
cordova.plugins.fileOpener2.open(
cdr.nativeURL + docFileNameToView,
'application/pdf', {
error: function(e) {
navigator.notification.alert("Error Opening the File.Unsupported document format.");
},
success: function() {
}
}
);
};
function fail(error) {
navigator.notification.alert("Error");
};
function errorHandler(e) {
navigator.notification.alert("Error");
};
function onGetDirectoryFail(error) {
navigator.notification.alert("Error");
};
This code uses cordova file transfer plugin to download pdf and file opener plugin to view the pdf. This sample code also use device plugin to get the device platform (iOS or Android) and dialog plugin to display notification.
Code was tested on iOS 9 and Android 6 devices and works fine. In Android, the file gets stored in storage/emulated/0/Cordova/My_App folder
If someone faces an issue while opening the file stored in device even with proper destination file path specified, please do ensure that the file is downloaded properly without corruption.
Many a times file opening fails due to improper or corrupted download. You can also trace any error during download using chrome inspect devices option. Also ensure to use latest version of file transfer plugin to avoid download error.
I am using fileDownload jQuery plugin to download a file which is served using ASP.NET MVC. The action is decorated with HttpGet and returns a FilePathResult. It works when a file is found. If a file is not found, I am not sure what to return in the action?
JavaScript:
function showMessageCancelDialog(message, request, titleValue) {
'use strict';
$('#messageDialog').html(message);
$('#messageDialog').dialog({
resizable: false,
width: '320px',
modal: true,
title: titleValue,
dialogClass: 'no-close',
buttons: {
Cancel: function () {
request.abort();
$(this).dialog("close");
}
}
});
}
function hideMessageDialog() {
'use strict';
$('#messageDialog').dialog("close");
}
function DownloadAttachment(itemId) {
'use strict';
var getAttachmentFileUrl = "/App/Download/GetAttachmentFile?ItemId=" + itemId;
var ajaxRequest = $.fileDownload(getAttachmentFileUrl, {
successCallback: function (message) {
hideMessageDialog();
},
failCallback: function (errorMessage) {
hideMessageDialog();
showMessageDialog("Download request failed:" + errorMessage, "Download attachment");
}
});
showMessageCancelDialog("Download in progress... , ajaxRequest, "Download attachment");
}
ASP.NET:
if(errorMessage == string.Empty)
{
this.Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadFile);
return new FilePathResult(downloadFile, "application/octet-stream");
}
else
{
// WHAT DO I RETURN HERE?
}
You could throw an error with your errorMessage and the jquery function failCallback() should catch that.
else {
throw new HttpException(404, errorMessage);
}
this.Response.Clear();
this.Response.StatusCode = 500;
this.Response.ContentType = "text/html";
this.Response.Write(errorMessage);
throw new Exception(errorMessage);
The above code called the failCallback on javascript
Below is mine Js Code.Multiple file selection working fine if I call FilesAdded event inside init method.but when I try to bind FilesAdded event to plupload object i.e uploader only first image file get uploaded to server rest discarded.
<script type="text/javascript">
// Custom example logic
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: 'Home/Upload',
flash_swf_url: 'Scripts/Moxie.swf',
silverlight_xap_url: 'Scripts/Moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
]
},
init: {
PostInit: function () {
document.getElementById('filelist').innerHTML = '';
},
UploadProgress: function (up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
uploader.init();
uploader.bind('FilesAdded', function () {
uploader.start();
});
</script>
Any help would be appreciated
put the below code after 'FilesAdded' event
uploader.bind('Error', function (up, err) {
console.log(err);
});
check the error code in console so that you can debug accordingly.
I have a strange behavior of extjs file upload.
The file upload defined as:
items: [{
xtype: 'filefield',
itemId: 'uploadandsign',
buttonText: NG.getLabel('browse'),
buttonOnly: true,
hideLabel: true,
width: 100
}]
If the file uploading is success I show successful label on the screen with remove "X" button:
onOpenFileBrowserChange: function (filefield, newValue, oldValue, eOpts) {
var me = this,
form = filefield.up('form').getForm(),
infoBox = invoiceorigin.down('#fileuploadinfoplaceholder'),
fileDescription,
secondfilefield,
customerFileName = newValue.replace(/^.*[\\\/]/, ''),
draft = me.getDraft(),
isSigned = true,
files = draft.files();
if (filefield.itemId === 'uploadandsign') {
isSigned = false;
secondfilefield = invoiceorigin.down('#uploadnosign');
fileDescription = 'File system, Unsigned';
}
secondfilefield.disable();
if (form.isValid()) {
form.submit({
url: NG.getLatestApiPath('WebInvoice', 'UploadInvoiceFile'),
waitMsg: NG.getLabel('webinvoiceInvoiceOriginUploadingFile'),
success: function (fp, o) {
if (o.result.success) {
var file = o.result.file;
files.add({
fileName: file.fileName,
createDate: file.createDate,
isAttachment: false,
isSigned: isSigned,
fileOrigin: fileDescription,
customerFileName: customerFileName,
invoiceFileOrigin: 'Local'
});
filefield.disable();
infoBox.removeAll();
infoBox.add(Ext.create('NG.view.webinvoice.InformationBox', {
data: {
closable: true,
icon: true,
iconCls: 'n-pdf-icon',
content: '<div class="n-text-overflow" style="width:145px;">' + fileDescription + '<br/>' + customerFileName + '</div>'
}
}));
}
else {
}
},
failure: function (form, action) {
}
});
}
return false;
},
Then if I remove the file from #infobox, the reset() function called:
onRemoveFileClick: function (view) {
var me = this,
invoiceorigin = view.up('invoiceorigin'),
uploadNoSignBtn = invoiceorigin.down('#uploadnosign'),
uploadAndSignBtn = invoiceorigin.down('#uploadandsign'),
infoBox = invoiceorigin.down('#fileuploadinfoplaceholder'),
draft = me.getDraft(),
files = draft.files(),
pagemanager = view.up('webinvoicepagemanager'),
invoiceFilePlace = files.findExact('isAttachment', false);
me.deleteFileConfirmReject(
NG.getLabel('webinvoiceInvoiceOriginDeleteInvoiceFileTitle'),
NG.getLabel('webinvoiceInvoiceOriginDeleteInvoiceFileMsg'),
function (buttonId, text, opt) {
if (buttonId == 'yes') {
infoBox.removeAll();
if (invoiceFilePlace > -1) {
files.removeAt(invoiceFilePlace);
}
me.fillInvoiceOriginStep(pagemanager);
uploadNoSignBtn.reset();
uploadAndSignBtn.reset();
uploadNoSignBtn.enable();
uploadAndSignBtn.enable();
}
});
}
After this action if I will choose the same file.... nothing happens with page... no any change event fired on the page.. However if I choose different file the behavior is OK.
In the ExtJS documentation said that the reset() function have to clear previous files uploads... however it does not helps.
Is any body met such file upload ExtJS behaivour and could help with this issue?
Thanks a lot.
What I tried and worked quite good was to get the file from the form with a typical JS document.getElementsByName('[name you gave]'); and it got perfectly the file uploaded without mattering in wich execution you are in.
Hope it helps.
When I try to write a file I am getting this error in Google Chrome:
Uncaught TypeError: Cannot read property 'root' of undefined FileSystemApi.html:29
onButtonSaveClick FileSystemApi.html:29
onclick
My sample code is as follows
var fileSys;
$(function () {
initFileSystem(onInitFileSystemSuccess);
});
function onInitFileSystemSuccess(fs) {
console.log('Opened file system: ' + fs.name);
fileSys = fs;
}
function onButtonSaveClick() {
alert('1');
var fileName = $("#fileName").val();
alert(fileName);
var fileContent = $("#fileContent").val();
alert(fileContent);
alert(fileSys.root);
fileSys.root.getFile(fileName, {
create: true,
exclusive: true
},
function (fileEntry) {
alert('2');
console.log('File opened: ' + fileEntry.fullPath);
fileEntry.createWriter(function (fileWriter) {
var blob = new Blob([fileContent], {
type: 'text/plain'
});
fileWriter.write(blob);
alert('done');
}, onFileSystemError);
}, onFileSystemError);
}
Would anyone be able to point out the problem(s), and, if so, contribute a solution?