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;
Related
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;
}
}
}
I can't to display file icons according to file extensions in asp.net GridView.
The structure of GridView is nested
The tutorial is Displays file icons in asp.net
The error is :
Object reference not set to an instance of an object
In this line of code-behind :
if (!String.IsNullOrEmpty(lnkDownload.Text))
My code below.
Can you help me?
Thank you in advance for any help, really appreciated.
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server"
AutoGenerateColumns="false" CssClass="mGrid" Width="700"
HorizontalAlign="Center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img id="fileImage" runat="server" src="" />
<asp:HiddenField ID="HiddenField1"
runat="server" Value='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-
HorizontalAlign="Justify">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text='<%#
Eval("Name") %>' CommandArgument=
'<%# Eval("FullName") %>' runat="server"
OnClick="lnkDownload_Click"
OnClientClick="if (!confirm('Confirm ?'))
return false;"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string root = #FilePath;
string folder = GridView2.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = (GridView)e.Row.FindControl("gvOrders");
Label gvLabel = (Label)e.Row.FindControl("gvLabel");
Label gvFolder = (Label)e.Row.FindControl("gvFolder");
DirectoryInfo directory = new DirectoryInfo(root + "/" + folder);
FileInfo[] fileInfo = directory.GetFiles("*.*",
SearchOption.AllDirectories);
fCount = directory.GetFiles("*.*",
SearchOption.AllDirectories).Length;
gvLabel.Text = fCount.ToString();
long size = 0;
foreach (string file in Directory.GetFiles(root + "/" + folder,
"*.*", SearchOption.AllDirectories))
{
size += new FileInfo(file).Length;
}
gvFolder.Text = Math.Round((double)size / (double)(1024 * 1024),
2).ToString() + " MB";
LinkButton lnkDownload =
(LinkButton)e.Row.FindControl("lnkDownload");
HiddenField hf = (HiddenField)e.Row.FindControl("HiddenField1");
if (!String.IsNullOrEmpty(lnkDownload.Text))
{
HtmlImage image = (HtmlImage)e.Row.FindControl("fileImage");
image.Attributes.Add("src", GetIconForFile(hf.Value));
}
gvOrders.DataSource = fileInfo;
gvOrders.DataBind();
}
}
private string GetIconForFile(string fileText)
{
string extension = Path.GetExtension(fileText);
extension = extension.Trim('.').ToLower();
return "~/fileicons/" + extension + ".png";
}
You have a Nested GridView Structure and gvOrders is your inner GridView. So, you've to get LinkButton from inner GridView's row as like:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvOrders = (GridView)e.Row.FindControl("gvOrders");
foreach (GridViewRow row in gvOrders.Rows)
{
LinkButton lnkDownload = (LinkButton)row.FindControl("lnkDownload");
HiddenField hf = (HiddenField)row.FindControl("HiddenField1");
if (!String.IsNullOrEmpty(lnkDownload.Text))
{
//... some code
}
}
}
}
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-disposition", "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
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.
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>