I have been working on an image/file uploader that stores an image to a virtual directory with MapPath or to a database. I have been using if statements for the button click event to check the file and attempt to save but I have not been successful.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string extension = Path.GetExtension(FileUpload1.FileName);
if (extension == ".jpg" || extension == ".gif" || extension == ".png" || extension == ".bmp")
{
FileUpload1.SaveAs(Server.MapPath("../photos/" + FileUpload1.FileName));
string imagePath = "/photos/" + FileUpload1.FileName;
please try this
FileUpload1.SaveAs(Server.MapPath(#"~\photos\" + FileUpload1.FileName));
Related
I use FileUpload control or HTML input type="file"
run on any Browser,chrome,I.E,android mobile.
It can run,only on IOS mobile do not work when Submit Button Click show "error"
<input type="file" name="UploadFile" id="UploadFile" class="form-control"/>
<asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click"/>
Code Behind
protected void Button_Click(object sender, EventArgs e)
{
HttpPostedFile postedFile = Request.Files["UploadFile"];
//Check if File is available.
if (postedFile != null && postedFile.ContentLength > 0)
{
string extension = Path.GetExtension(postedFile.FileName);
if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
{
Div1.Style["display"] = "flex";
Label7.Text = "*CHOOSE(.png 或 .jpg 或 .jpeg)!! ";
return;
}
string filename = Path.GetFileName(postedFile.FileName);
string path = "";
path = "~/CustomerFeedbackPic/" + filename;
string serverDir = "";
serverDir = Server.MapPath(path);
postedFile.SaveAs(serverDir);
Response.Redirect("uploadsuccess.aspx");
}
}
In my application i am using one Fileupload controller ,one dropdown and One button, Here first i am selecting one .doc file using fileupload controller, then i am selecting Dropdown value, when i am clicking button, it checks dropdown value is > 0 or not,
if (ddlstype.SelectedValue != "0")
if the ddlstype value is equals 0, then it shows an Error message in label.
Here the dropdown have AutoPostBack,code follows,
<asp:DropDownList ID="ddlstype" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlstype_SelectedIndexChanged" Width="165px">
Here my problem is if the page is AutoPostBack, then the file upload control become null, how can i maintain the file in fileupload controler while AutoPostBack?
Here you store file path in session on page load. This way you not need to use update panel
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
if (Session["FileUpload1"] == null && Request.Files["FileUpload1"].ContentLength > 0)
{
Session["FileUpload1"] = Request.Files["FileUpload1"];
ImageErrorLabel.Text = Path.GetFileName(Request.Files["FileUpload1"].FileName);
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
}
else if (Session["FileUpload1"] != null && (Request.Files["FileUpload1"].ContentLength == 0))
{
HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
ImageErrorLabel.Text = Path.GetFileName(file.FileName);
}
else if (Request.Files["FileUpload1"].ContentLength > 0)
{
Session["FileUpload1"] = Request.Files["FileUpload1"];
ImageErrorLabel.Text = Path.GetFileName(Request.Files["FileUpload1"].FileName);
}
}
}
And get it on ddlstype_SelectedIndexChanged
protected void ddlstype_SelectedIndexChanged(object sender, EventArgs e)
{
HttpPostedFile FileUpload1 = Request.Files["FileUpload1"];
Session["FileUpload1"] = FileUpload1;
}
i am making a notepad in c#. this is the save part of the file. but the problem is that if i modify the text and save again, it asks to save a new file instead of saving in original file.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file";
saveFileDialog1.FileName = tabControl1.SelectedTab.Text;
saveFileDialog1.Filter = "TEXT|*.txt|DOC|*.doc|DOCX|*.docx|RICH TEXT FILE|*.rtf|ALL FILES|*.*";
saveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName != "")
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
Use a private field in your class that has the value of the last saved file
var currentFileName = "";
.....
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file";
saveFileDialog1.FileName = tabControl1.SelectedTab.Text;
saveFileDialog1.Filter = "TEXT|*.txt|DOC|*.doc|DOCX|*.docx|RICH TEXT FILE|*.rtf|ALL FILES|*.*";
saveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
bool save = true;
if (string.IsNullOrEmpty(currentFileName))
{
var result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK && saveFileDialog1.FileName != "")
{
currentFileName = saveFileDialog1.FileName;
}
else
{
save = false;
}
}
if (save)
richTextBox1.SaveFile(currentFileName, RichTextBoxStreamType.RichText);
}
If you keep showing the save file dialog then this is what you get. (saveFileDialog1.ShowDialog())
Best would be:
Create internal string variable containing the path. (default is "") (or use tabControl1.SelectedTab.Text)
If path is not set, show file dialog, save result in path
If path is set, save file
set .OverWritePrompt to false for your SaveFileDialog
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.overwriteprompt.aspx
Okay, so I'm working with some if/else statements now. But, I'm having some trouble.
Here's the full code that is depending on the version clicked.
private void button_Click(object sender, EventArgs e)
{
using (OpenFileDialog file = new OpenFileDialog())
{
file.Filter = "File(*.file)|*.jar|All Files (*.*)|*.*";
file.Title = "Open File...";
if (file.ShowDialog() == DialogResult.OK)
{
string fullFileName = item.FileName;
FileInfo userSelected = new FileInfo(fullFileName);
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
string mcAD = Environment.ExpandEnvironmentVariables("%AppData%");
File.Copy(item.FileName, mcAD, true);
}
}
But what I'm having trouble is with this.
Below is the code, but here's how the program is lain out.
There's a menu at the bottom of the program. It's named "Version" you click and you can choose version 1.0, 2.0, and 3.0. I have it set so there's text beside it telling it which version you chose.
Now, the issue is I need an if/else statement for all the version for the above code cause all files for each version go to a different location.
Here's the other code...
private void Version_1_0_Click(object sender, EventArgs e)
{
string Version_1_0_Selected = VersionText.Text = "1.0 Selected";
}
private void Version_1_6_1_Click(object sender, EventArgs e)
{
string Version_2_0_Selected = VersionText.Text = "2.0 Selected";
}
private void Version_3_0_Click(object sender, EventArgs e)
{
string Version_3_0_Selected = VersionText.Text = "3.0 Selected";
}
You can use Control.Tag for storing version index. For example:
private void Version_1_0_Click(object sender, EventArgs e)
{
VersionText.Text = "1.0 Selected";
VersionText.Tag= 1;
}
Then, you can define your target paths:
string[] paths = {#"c:\path1.txt", #"c:\path2.txt", #"c:\path3.txt"};
Finally, when you writing your files you can lookup the path like this:
File.Copy(item.FileName, paths[VersionText.Tag], true);
You might need to modify this code if the target file name is based on the source file name, but that should not be difficult.
Abstract the FileDialog code to a separate method and pass in your version string so that you can then perform the checks.
public void OpenVersionDialog(string version)
{
string mcAD = GetCopyPath(version);
if(!String.IsNullOrEmpty(mcAD))
{
using (OpenFileDialog file = new OpenFileDialog())
{
file.Filter = "File(*.file)|*.jar|All Files (*.*)|*.*";
file.Title = "Open File...";
if (file.ShowDialog() == DialogResult.OK)
{
string fullFileName = item.FileName;
FileInfo userSelected = new FileInfo(fullFileName);
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
File.Copy(item.FileName, mcAD, true);
}
}
}
else
{
//invalid version selected
}
}
public string GetCopyPath(string versionInput)
{
//these are case-insensitive checks but you can change that if you want case-sensitive
if(string.Equals(versionInput, "1.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 1.0";
if(string.Equals(versionInput, "2.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 2.0";
if(string.Equals(versionInput, "3.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 3.0";
return String.Empty;
}
If I understand correctly that should be what you want. If you have more versions, you could store them in a dictionary where the key is the version and the value is the path that the file should be copied to.
I'm not sure what the difference between mcAD and destPath is but I assume mcAD is the variable that changes based on the version as that's being used in File.Copy.
protected void Page_Load(object sender, EventArgs e)
{
field1.Text = (string)(Session["rolename"]); //from the page before. eg:IT Folder
field2.Text = (string)(Session["fullname"]);
if (Page.IsPostBack == false)
{
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo("C:\\Documents and Settings\\itdept\\Desktop\\Files\\"+ field1.Text);
TreeNode RootNode = OutputDirectory(RootDir, null);
MyTree.Nodes.Add(RootNode);
}
}
protected void click(object sender, EventArgs e) //onselectednodechanged from the treenode in aspx page
{
string file = ("C:\\Documents and Settings\\itdept\\Desktop\\Files\\" + field1.Text + "\\" + MyTree.SelectedValue);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + file);
Response.ContentType = "text/xml";
Response.WriteFile(file); // here is the problem
Response.End();
}
**i can download files from the IT Folder, but in case there is a folder inside the IT Folder and i want to download something from that folder, i cannot download it.
does anyone have an idea how to make all things inside a folder even in a folder is downloadable?
thank you. :D