I am saving (uploading) file to FTP server using file upload control and .SaveAs method. But after 1st post back session values are lost. Not sure why and any work around this.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TheUser"] != null)
{
aUser = (clsUser)Session["TheUser"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)//continue only if the file control has the file
{
if (Get_and_Show_FileInformation())//if the file information was retrived and loaded into the textboxes
{
//continue with the execution
}
else
{
//error message displyed
}
}
}
protected bool Get_and_Show_FileInformation()
{
if (FileUpload1.HasFile)
{
string fName = FileUpload1.PostedFile.FileName;
string extension = Path.GetExtension(fName);
string FileName = fName.Substring(0, fName.Length - extension.Length);
string dir = uname;
string appPath = Server.MapPath("Uploads/") + dir;
FileInfo MyFileInfo = new FileInfo(appPath);
DirectoryInfo newDirectoryInfo = new DirectoryInfo(appPath);
if (!Directory.Exists(appPath))//if user is uploading to FTP_Upload first time, create a new directory for him/her
{
try
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + dir + "/" + FileName)); // ERROR here, call to this .SaveAs method causes loss of session values (Session["TheUser"])
Image2.ImageUrl = "~/Uploads/" + dir + "/" + FileName;
return true;
}
catch (Exception ex)
{
lbl_Err.Text = "<br/>Error: Error creating and saving into your space!(Error Code:XF05)";
return false;
}
}
else
{
//same code but don't create the directory
}
}
}
Related
private void pdfButton_Click(object sender, EventArgs e)
{
Operation.RunMacro("ExportPDF.cs");
if (Operation.RunMacro == )
{
MessageBox.Show("PDF files exported!");
pdfLabel.Text = pdfLabel.Text + " - DONE!";
pdfLabel.ForeColor = System.Drawing.Color.Green;
}
else
{
pdfLabel.Text = pdfLabel.Text + " WRONG!";
pdfLabel.ForeColor = System.Drawing.Color.Red;
}
}
This is my body of code, when the pdfButton is clicked, the macro will run opening up my file window. From there the user names their files and stores to a folder, how can I make the if statement execute when they store their files?
The method Operation.RunMacro needs to return the operation result. Then you have a condition you can test against:
class Operation
{
public bool RunMarco(string fileName)
{
try
{
// export logic
...
return true;
}
catch
{
return false;
}
}
}
then you can do:
private void pdfButton_Click(object sender, EventArgs e)
{
bool runMacroResult = Operation.RunMacro("ExportPDF.cs");
if (runMacroResult)
{
MessageBox.Show("PDF files exported!");
pdfLabel.Text = pdfLabel.Text + " - DONE!";
pdfLabel.ForeColor = System.Drawing.Color.Green;
}
else
{
pdfLabel.Text = pdfLabel.Text + " WRONG!";
pdfLabel.ForeColor = System.Drawing.Color.Red;
}
}
I defined a string variable at class level and set this variable in protected void UploadButton_Click(object sender, EventArgs e) after uploading the file successfully.
I do this so that i can pass value of fileName variable from this function to another
protected void btnSave_Click(object sender, EventArgs e) {} where i save it in the database. but value always is null. Am i doing something wrong or it remain null as functions are defined as Protected type
public partial class News: System.Web.UI.Page
{
string _fileName = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// some code here......
}
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
System.IO.FileInfo f = new System.IO.FileInfo(FileUploadControl.PostedFile.FileName);
if (f.Extension.ToLower() == ".pdf" || f.Extension.ToLower() == ".doc" || f.Extension.ToLower() == ".docx")
{
//3MB file size
if (FileUploadControl.PostedFile.ContentLength < 307200)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
if (!System.IO.File.Exists("../pdf/news/" + FileUploadControl.FileName))
{
FileUploadControl.SaveAs(Server.MapPath("../pdf/research/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
_fileName = FileUploadControl.FileName;
}
else
{
_fileName = null;
StatusLabel.Text = "File with this name already exsists, Please rename file and Upload gain";
}
}
else
{
_fileName = null;
StatusLabel.Text = "Upload status: The file has to be less than 3MB!";
}
}
else
{
_fileName = null;
StatusLabel.Text = "Upload status: Only PDF or Word files are accepted!";
}
}
catch (Exception ex)
{
_fileName = null;
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
ASP.NET WebForms doesn't quite work like you expect it to... You have to understand the page life cycle.
Basically, at each request, your page object is recreated from scratch. The two button clicks will generate two requests, and so you'll get two page instances, one for each request. You can't share data between them this way.
You have several ways to overcome this:
Use the ViewState for this. This is an object that is basically serialized, then sent to the client. The client sends it back at each postback, and it's deserialized so you can access it. So do not put sensitive data inside. There are facilities that let you encrypt this data though.
Use the Session. But this can become messy pretty quick, and you'll have to deal with the case when the user opens serveral instances of the same page.
I'm working with displaying files from the server's Z:/File Directory. The problem is, while the PDF and JPEG/JPG files render correctly inside the Iframe in localhost, when I use the IIS server IP name, 192.168.xxx.xxx:8081/Home.aspx, they do not render. I also have a download button in which the user can.. well download files. The Iframe and the download button points to the same source, but the Iframe does not return/display the file correctly. It just shows blank.
Here is an example of the source URL: \192.168.xxx.xxx\Z$\File Directory\PDF Files\cyber.pdf.
Oh and BTW, I also map them to the Iframe and download button dynamically.
protected string GetPath(TreeNode treenode)
{
string[] array = new string[100];
string path = string.Empty;
int depth = treenode.Depth;
TreeNode node = new TreeNode();
node = treenode;
array[0] = node.Value;
for (int i = 1; i <= depth; i++)
{
array[i] = node.Parent.Value;
node = node.Parent; ;
}
//path = "~/";
path = #"\\192.168.3.12\Z$\";
for (int i = depth; i >= 0; i--)
{
if (Path.GetExtension(array[i].ToString()) == string.Empty)
{
//path += array[i].ToString() + "/";
path += array[i].ToString() + #"\";
}
else
path += array[i].ToString();
}
return path;
}
protected void trvNews_SelectedNodeChanged(object sender, EventArgs e)
{
try
{
if (trvNews.SelectedNode.Expanded == true)
{
trvNews.SelectedNode.Collapse();
trvNews.SelectedNode.Selected = false;
}
else if(trvNews.SelectedNode.Expanded == false)
trvNews.SelectedNode.Expand();
if (trvNews.SelectedNode.ChildNodes.Count == 0)
{
if (Path.GetExtension(trvNews.SelectedNode.Text) == string.Empty)
{
hfPath.Value = GetPath(trvNews.SelectedNode);
//ListDirectory(trvNews, Server.MapPath(hfPath.Value), "NoChild");
ListDirectory(trvNews, hfPath.Value, "NoChild");
Session["Count"] = "Enabled";
}
else
{
string test2 = Path.GetFullPath(hfPath.Value);
string path = hfPath.Value + trvNews.SelectedNode.Text;
//site = "DocumentViewer.aspx?=" + Path.GetFileName(path);
string url = "DocumentViewer.aspx?=" + Path.GetFileName(path);
Session["Path"] = path;
//ClientScript.RegisterStartupScript(typeof(Page), "Sigma", "open_win()", true);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "newpage", "open_win('" + url + "');", true);
Session["Count"] = "Enabled";
}
}
string test = Session["Count"].ToString();
if (Session["Count"].ToString() == "Enabled")
btnBack.Visible = true;
}
catch (Exception ex)
{
LogError(ex, "User");
}
}
This is the code in the first page as the user clicks the file to view/download it. The next page is..
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
string path = Session["Path"].ToString();
int length = path.Length;
lblHead.Text = Path.GetFileName(path);
System.IO.FileInfo file = new System.IO.FileInfo(Session["Path"].ToString());
if (Path.GetExtension(path) == ".pdf")
{
pnlPdf.Visible = true;
if (Session["FromNews"] != null)
framePdf.Attributes["src"] = FormulatePathPDFNews(path);
else
{
framePdf.Attributes["src"] = "\\\\" + file.FullName;
}
}
else if (Path.GetExtension(path) == ".jpeg" || Path.GetExtension(path) == ".jpg")
{
pnlJpeg.Visible = true;
//imageJpeg.Attributes["src"] = FormulatePath(path);
imageJpeg.Attributes["src"] = file.FullName;
}
}
}
catch (Exception ex)
{
LogError(ex, "User");
}
}
The download button for this is:
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
if (Path.GetExtension(Session["Path"].ToString()) != null)
{
System.IO.FileInfo file = new System.IO.FileInfo(Session["Path"].ToString());
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
Response.Write("This file does not exist.");
}
}
catch (Exception ex)
{
LogError(ex, "User");
}
}
They are working perfectly fine in localhost, but does not display when in IIS server. Any tips?
Most of the time this would indicate that the path cannot be found or the folder required permissions.
The site will run under a specific user (Look at the Identity in the Application Pool), that user will need permissions to the folder.
I am using DropNet. I have problem with upload file into DropBox.
I am sure the connection with dropbox in fine. when I changed the method of upload to create file and delete file method that works fine.
I really can not see any problem that why is not uploading? I use exactly same API as DropNet.
protected void Btn_upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Session["DropNetUserLogin"] != null)
{
try
{
_client.UseSandbox = true;
_client.UploadFile("/", FileUpload1.FileName, FileUpload1.FileBytes);
}
catch (Exception ex)
{
litOutput.Text = "Error in upload user login in session " + ex.Message;
}
}
else
{
litOutput.Text = "Session expired...";
}
}
else
{
litOutput.Text = "You did not specify a file to upload.";
}
}
}
Here is code which worked for me, hoping that this may help you:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
FileNameTextBox.Text = filename;
}
var x = #"/" + Path.GetFileName(FileNameTextBox.Text);
_client.UploadFile("/", Path.GetFileName(FileNameTextBox.Text), File.ReadAllBytes(#"" + FileNameTextBox.Text));
}
In my code I write the value from DropDownList1.SelectedItem.Text to Label1.Text and into uploadFolder in the DropDownList1_SelectedIndexChanged method. When the ASPxUploadControl1_FileUploadComplete method is called, the value is in Label1.Text but not in uploadFolder, which is null. Why is this?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
uploadFolder = DropDownList1.SelectedItem.Text;
}
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
string path = (uploadDirectory + uploadFolder + "/" + fileName);
//string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}
It looks like uploadFolder is a variable you've declared on your page, something like this:
public class MyPage : System.Web.UI.Page
{
string uploadFile = null;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Your code here
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
// Your code here
}
}
What's happening is that the content of uploadFile that you're setting in DropDownList1_SelectedIndexChanged isn't being preserved between post-backs, because it isn't a property of one of the controls on the page. You need to store the value somewhere that gets persisted, such as the View State or in Session State.
To do this, you should add to the DropDownList1_SelectedIndexChanged method so it reads something like:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
Session["UploadFolder] = DropoDownList1.SelectedItem.Text;
}
}
And adjust the ASPxUploadControl1_FileUploadComplete method so it extracts `uploadFolder from the Session:
string path = (uploadDirectory + Session["UploadFolder"] + "/" + fileName);
If you want to make it look more elegant than that, consider using ViewState in this sort of way:
public string UploadFolder
{
get
{
return (string)ViewState["UploadFolder"];
}
set
{
ViewState["UploadFolder"] = value;
}
}
You can then do this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
UploadFolder = DropoDownList1.SelectedItem.Text;
}
}
And:
string path = (uploadDirectory + UploadFolder + "/" + fileName);
I would imagine that you are not persisting uploadFolder through page post backs. Store the value in a hidden field, e.g.:
<asp:HiddenField ID="hidden_UploadFolder" runat="server" />
And then:
hidden_UploadFolder.Value = DropDownList1.SelectedItem.Text;
You can then read it again on the next post back:
string uploadFolder = hidden_UploadFolder.Value;
Make sure you add error trapping.
It looks like you are setting the value for upload folder in one postback and using it in another. If you want to persist data between postbacks use the Session.
ex.
Session["uploadFolder"] = DropDownList1.SelectedItem.Text;
string path = (uploadDirectory + Session["uploadFolder"].ToString() + "/" + fileName);
Try
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
Session["uploadFolder"] = DropDownList1.SelectedItem.Text;
}
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
string uploadfolder = Session["uploadFolder"] as String;
string path = (uploadDirectory + uploadfolder + "/" + fileName);
//string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}