WHY ASP.NET FileUpLoad do not run in IPhone IOS - c#

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");
}
}

Related

How to Maintain File In FileUpload controller while AutoPostBack

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;
}

Upload files in Gridview and display in the same row upon completion

I am trying to store files from a Gridview upload into a Folder using Asp.net.
This is my markup code to generate Upload column and The button and File Upload control.
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" CommandName="Upload" Text="OK" style=" color: #ff0000" OnClick="btnUpload_Click"/>
</ItemTemplate>
</asp:TemplateField>
I have my codebehind to handle btnUpload_Click as below:
protected void btnUpload_Click(object sender, GridViewCommandEventArgs e)
{
Response.Write("File has been passed");
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload4") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fleUpload = Path.GetExtension(fu.FileName.ToString());
if (fleUpload.Trim().ToLower() == ".xls" | fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
//Someting to do?...
}
else
{
upload = false;
// Something to do?...
}
if (upload)
{
// somthing to do?...
}
}
else
{
//Something to do?...
}
}
I am getting this error:
CS0123: No overload for 'btnUpload_Click' matches delegate
'System.EventHandl
Can somebody please help me?
You're binding both Command and Click event with your button. Your button code should be like this-
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" CommandName="Upload" Text="OK" style=" color: #ff0000"/>
</ItemTemplate>
</asp:TemplateField>
and from code behind capture the command not the event. like-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Write("File has been passed");
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload1") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fileName = Path.GetFileName(fu.PostedFile.FileName);
string fleUpload = Path.GetExtension(fu.PostedFile.FileName);
if (fleUpload.Trim().ToLower() == ".xls" || fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fileName));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fileName ));
//Someting to do?...
}
else
{
upload = false;
// Something to do?...
}
if (upload)
{
// somthing to do?...
}
}
else
{
//Something to do?...
}
}
above I'm assuming your gridview ID is GridView1. And another one your File Uploader control's ID was mismatched with your code behind. This should work.

ASHX handler throwing value cannot be null error

I wanted to display a list of files in a specific folder as hyperlinks, and when the user click on the link, it will open the respective file to prompt the user to download or view but there is a constant error saying:
{"Value cannot be null.\r\nParameter name: filename"} at the line context.Response.WriteFile(context.Request.QueryString["files"]);
I've tried lots of ways but to no avail.
ASHX file:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var directory = new DirectoryInfo("C:\\temp\\Safety&Security");
var files = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
//string[] files = Directory.GetFiles(#"C:\temp\Safety&Security");
//files = files.Substring(files.LastIndexOf(("\\")) + 1);
rpt.DataSource = files;
rpt.DataBind();
}
if (!Page.IsPostBack)
{
string[] files = Directory.GetFiles(#"C:\temp\marketing");
Repeater1.DataSource = files;
Repeater1.DataBind();
}
if (!Page.IsPostBack)
{
string[] files = Directory.GetFiles(#"C:\temp\IT");
Repeater2.DataSource = files;
Repeater2.DataBind();
}
}
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
string file = e.Item.DataItem as string;
HyperLink hyp = e.Item.FindControl("hyp") as HyperLink;
hyp.Text = file;
hyp.NavigateUrl = string.Format("~/Handlers/FileHandler.ashx?file={0}", file);
FileInfo f = new FileInfo(file);
FileStream s = f.Open(FileMode.OpenOrCreate, FileAccess.Read);
}
}
public void ProcessRequest(HttpContext context)
{
//Track your id
//string id = context.Request.QueryString["id"];
context.Response.Clear();
context.Response.Buffer = true;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["files"]);
context.Response.WriteFile(context.Request.QueryString["files"]);
context.Response.End();
}
public bool IsReusable
{
get { return false; }
}
This is the index page codes:
<li class='has-sub'><a href='#'><span>Safety, QA & Security</span></a>
<ul>
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
<ItemTemplate>
<asp:HyperLink ID="hyp" runat="server" target="_blank" a href="/Handlers/FileHandler.ashx?id=7"/>
<%-- another method of listing all files in specific folder --%>
<%--<% foreach(var file in Directory.GetFiles("C:\\temp\\Safety&Security", "*.*", SearchOption.AllDirectories)) { %>
<li><%= file.Substring(file.LastIndexOf(("\\"))+1) %></li>
<% } %> --%>
</ItemTemplate>
</asp:Repeater>
</ul>
</li>
You've made a silly mistake!
hyp.NavigateUrl = string.Format("~/Handlers/FileHandler.ashx?file={0}", file);
context.Response.WriteFile(context.Request.QueryString["files"]);
You're setting the querystring as 'file' but reading the querystring as 'files' which doesn't exist. Try
context.Response.WriteFile(context.Request.QueryString["file"]);
EDIT:
Try this code. First add a file in your c:\temp called test.txt and put some text in there. In your aspx:
<li class='has-sub'><a href='/Handlers/FileHandler.ashx?file=c:\temp\test.txt'><span>Safety, QA & Security</span></a></li>
In your handler:
public void ProcessRequest(HttpContext context)
{
//Track your id
//string id = context.Request.QueryString["id"];
context.Response.Clear();
context.Response.Buffer = true;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["file"]);
context.Response.WriteFile(context.Request.QueryString["file"]);
context.Response.End();
}
public bool IsReusable
{
get { return false; }
}
Set a breakpoint in your handler and make sure your handler gets hit when you debug. This code won't work as you need it to because of the other problem I mentioned in the comments about your data binding not working but you should at least get the querystring in your handler and the text file will download.

How to find dynamic control inside a dynamically added container

In my website I am uploading photos through asp:FileUpload [multiple files - images].. After uploading I am displaying them in a Panel along with a textbox to write description for the uploaded Images. Then am going to save them in database. But I am not able to find the values of the textbox or find the controls I have added to the panel when in my save event. But the images and textbox will be displayed in the panel.
My frontend code is something like this:
<form id="form1" runat="server">
<div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
<asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
<asp:Button runat="server" ID="uploadedFile" style="position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
<asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
<asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" Font-Bold="true" BackColor="Yellow" />
</asp:Panel>
</div>
</form>
and my backend code is something like this:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
int tid = 0;
string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
{
HtmlGenericControl dh = new HtmlGenericControl("div");
dh.Attributes.Add("class", "head");
dh.InnerText = "Write Description";
updtpanel.Controls.Add(dh);
HtmlGenericControl dload;
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
tid = tid + 1;
textid = "txt" + tid;
Image img = new Image();
TextBox ta = new TextBox();
ta.TextMode = TextBoxMode.MultiLine;
filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
uploadedFile.SaveAs(filepath);
newpath = "../Images/Gallery/" + uploadedFile.FileName;
try
{
dload = new HtmlGenericControl("div");
updtpanel.Visible = true;
dload.Attributes.Add("class", "dataload");
dload.Attributes.Add("runat", "server");
dload.ID = "ind" + tid;
img.CssClass = "loadimg";
img.ImageUrl = newpath.ToString();
img.ID = "img"+tid;
img.Attributes.Add("runat", "server");
ta.Attributes.Add("class", "txtdes");
ta.ID = textid;
ta.Attributes.Add("runat", "server");
dload.Controls.Add(img);
dload.Controls.Add(ta);
updtpanel.Controls.Add(dload);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);
}
}
protected void btnsave_Click(object sender, EventArgs e)
{
foreach (Control c in updtpanel.Controls)
{
cnt1 += 1;
HtmlGenericControl div = ((HtmlGenericControl)updtpanel.FindControl("ind"+cnt1.ToString()));
foreach (Control nc in div.Controls)
{
string str = "";
string iurl = "";
TextBox txt = (TextBox)div.FindControl("txt" + cnt1.ToString());
Image img = (Image)div.FindControl("img" + cnt1.ToString());
str = txt.Text;
iurl = img.ImageUrl;
id += 1;
string Insert = "Insert into slider (slid,slurl,slalt) values (#id,#IMAGE_PATH,#alter)";
SqlCommand cmd = new SqlCommand(Insert, con);
cmd.Parameters.AddWithValue("#IMAGE_PATH", iurl);
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#alter", str);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e1)
{
Response.Write(e1.Message);
}
}
}
updtpanel.Visible = false;
}
But its giving an error while saving which says object reference not set to an instance of the object after Findcontrol in save click event. Where I am going wrong. I am really working this from past 3 days but still not able to get it. Please show me a way out of this.
Is there anything else I need to add to this? I came across some site where some of them said that controls need to be recreated in Page_Load after postback. But when I am creating controls in an event How can I recreate them back in Page_Load.
Try this.Works for me try replacing the contentplaceholder with the form id may work.
String Value= (this.Form.FindControl("ContentPlaceHolder1").FindControl("panel").FindControl("txtbx" ) as TextBox).Text;

File Upload for asp.net in c#

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));

Categories

Resources