Why the image does not enter a variable? - c#

aspx:
<asp:FileUpload runat="server" ID="PicUpload" CssClass="btn btn-sm xor"/>
aspx.cs:
PicUpload.SaveAs(Path.Combine("C:\\Users\\KeepKids\\KeepKids\\pics\\", PicUpload.FileName));
why PicUpload.FileName ="" ?
In one place I do the same action and I get the picture. and here I get ""

I am find from below link:
https://www.aspforums.net/Threads/136183/ASPNet-FileUpload-control-Issue-FileName-is-blank-always-blank/
Can you please try this:
**PicUpload.PostedFile.FileName**
Something like below:
protected void btnsubmit_Click(object sender, EventArgs e)
{
string filename = "";
if (uploadphoto.PostedFile != null)
{
filename = Path.GetFileName(uploadphoto.PostedFile.FileName);
if (filename != "")
{
uploadphoto.SaveAs(Server.MapPath("images/" + filename));
string path = "images/" + filename;
}
}
}

<asp:FileUpload ID="FileUploadControl" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File"
onclick="UploadButton_Click" />
<br />
<asp:Label ID="lblMessage" Font-Bold="true" runat="server">
</asp:Label>
Below is the click event which picks up the filename from FileUploadControl
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
lblMessage.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
lblMessage.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}

Related

FileUpload.HasFile is always returning false

FileUpload.HasFile is always returning false
<asp:FileUpload id="FileUploadControl" runat="server" style="width:240px;" />
<br />
<asp:Label runat="server" id="StatusLabel" text="" />
<asp:Button runat="server" ID="btn1" OnClick="btn1_Click" />
protected void btn1_Click(object sender, EventArgs e)
{
string filename = "";
if (FileUploadControl.HasFile)
{
try
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename);
StatusLabel.Text = filename;
}
catch (Exception ex)
{
string str = ex.Message;
}
}
}

File Downloading Error in ASP.NET - C# from Gridview

Kindly Look at the error screen. I just want to download file from template field in gridview I saving file in server directory and file path in db.
any with this fix or proper new solution
<asp:GridView ID="GridView1" runat="server"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("filepath") %>' runat="server" OnClick = "FilesDownload"></asp:LinkButton>
--%>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download"
Text='<%# Eval("Path") %>' CommandArgument='Eval("Path")'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{ Response.Clear(); Response.ContentType = "application/octectstream";
Response.AppendHeader("content-dispositi­on", "filename=" + e.CommandArgument);
Response.TransmitFile(Server.MapPath("~/­File") + "//" + e.CommandArgument);
Response.End(); }
}
You need to follow the below steps:-
Add the TemplateField at the end as below.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("file") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and in Code-behind do something like this:-
protected void DownloadFile(object sender, EventArgs e)
{
try
{
string filePath = (sender as LinkButton).CommandArgument;
System.Net.WebClient req = new System.Net.WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath("~/YourFolder/" + filePath) + "\"");
byte[] data = req.DownloadData(Server.MapPath("~/YourFolder/" + filePath));
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
throw ex;
}
}
Reference link:- http://www.aspsnippets.com/Articles/Download-Files-from-GridView-using-LinkButton-Click-Event-in-ASPNet-using-C-and-VBNet.aspx
Hope that helps

Asyncupload control of AjaxControlToolkit

I am using asyncupload control of AjaxControlToolkit and I want to check the file to be uploding is already exists or
not on server.
How we can do this?
Please help me out.
<!-- Client side code for control-->
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
<!-- Control Code in aspx-->
<tr>
<td></td>
<td>
<cc1:AsyncFileUpload ID="FileUpload2" Width="265px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red"
ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../../images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:HiddenField ID="hdnField" runat="server" value=""/>
</td>
</tr>
//.CS Code for ayncupload control
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath="C:\Documents\temp.txt"
if(File.Exists(filePath))
{
hdnField.value="1";//Not able to access this value
}
}
Thanks!!
you just need to set your hidden field value at client side script.
See I have made little changes in your server side code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath = "C:\\Documents\\temp.txt";
string hiddenValue = "0";
if (File.Exists(filePath))
{
hiddenValue = "1";
}
//This script will set required value for hidden field.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetHiddenField", String.Format("top.$get('{0}').value = '{1}'", hdnField.ClientID, hiddenValue), true);
}
Make changes in your script location as follow:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
Check if the file exists using the following:-
File.Exists
You can compare based on the filename.

Doc file does not download from UserControl in asp.net

I have user control which contain a grid with candidate data. There a columns candidate name with template field link button. I have attached a rowcommand event on which I am downloading a word file. I have download doc file code which download my doc file from simple web page but this code is not working on user control. Can any one help me to out this problem. its giving the error response is not available
<asp:GridView ID="grdCandidate" runat="server" AutoGenerateColumns="false"
OnRowDataBound="grdCandidate_RowDataBound"
onrowcommand="grdCandidate_RowCommand">
<Columns>
<asp:BoundField DataField="Candidate ID" HeaderText="Candidate ID" />
<asp:TemplateField>
<HeaderTemplate>
Candidate Name
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkResume" CommandName="Download" CommandArgument='<%#Eval("Candidate ID") %>'
runat="server" Text='<%#Eval("Candidate Name") %>' ToolTip='<%# "Download Resume - " + Eval("Candidate Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCandidate_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Download")
{
byte[] Attachment = null;
string Extension = string.Empty;
string Resume = "Resume";
ClsCandidateManager objCandidateManager = new ClsCandidateManager();
ClsSecureManager objSecureManager = new ClsSecureManager();
Attachment = objCandidateManager.GetCandidateAttachment(Convert.ToInt32(e.CommandArgument), out Extension);
if (Attachment != null && Attachment.Length > 0)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
if (Extension == ".pdf")
{
Response.ContentType = "application/pdf";
}
else
{
Response.ContentType = "application/vsd-msword";
}
Response.AddHeader("content-disposition", "attachment;filename=" + Resume + Extension);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(Attachment);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
string str = ex.Message + ex.InnerException;
}
}
else
{
//ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Resume is not Uploaded !');</script>");
}
}
}
catch (Exception ex)
{
string str = ex.Message + ex.InnerException;
}
Use the UpdatePanel as shown below,
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="View" OnClick="lnkDownload_Click"
CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lnkDownload" />
</Triggers>
</asp:UpdatePanel>

Upload a file using AsyncFileUpload Control and store it

I am doing a project :
Front end - Visual Studio 2010
Technology : C#
Back end - Sql Server 2005
I am trying to upload a file using AsyncFileUpload Control and store it to "~/Image/" folder.
Script :
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"/>
</ContentTemplate>
Code Behind :
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.HasFile)
{
AsyncFileUpload1.SaveAs("~/Image/" + AsyncFileUpload1.FileName);
Label2.Text = "Recieved " + AsyncFileUpload1.FileName + " Content Type" + AsyncFileUpload1.PostedFile.ContentType;
}
}
But everytime its showing runtime error called :
The SaveAs method is configured to require a rooted path, and the path '~\Image\Filename.jpg' is not rooted.
May I know the error and its solution.
Thanks in advance,
Nikhil
I figured it out:
table width="100%" style="font: 8pt verdana">
<tr width="100%">
<td width="40%">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:HiddenField ID="HiddenField1" runat="server" />
</td>
<td width="40%"><asp:Label ID="lblPicStatus" runat="server"></asp:Label></td>
<td>
<asp:Button ID="Button2" runat="server" Text="Upload" BackColor="White"
BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px"
onclick="Button2_Click"/></td>
</tr>
</table>
Code Behind,
protected void Button2_Click(object sender, EventArgs e)
{
try
{
con.Open();
if (FileUpload1.HasFile)
{
String fileExt = Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png")
{
String path = "~/Image/" + FileUpload1.FileName;
cmd.CommandText = "update " + HttpContext.Current.User.Identity.Name + " set image = '" + path + "'";
cmd.Connection = con;
cmd.ExecuteNonQuery();
FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
Response.Redirect(Request.RawUrl);
}
else
{
lblPicStatus.Text = "File to be uploaded is not an image";
}
con.Close();
}
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
String path = "~/Image/" + FileUpload1.FileName;
Should be like this:
String path = Server.MapPath("~/Image/") + FileUpload1.FileName;

Categories