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
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
}
}
}
}
In below code image search from Google and display it.
i add one link-button in every image that is download.
Now problem is get some error when i download image .
Error is " ... is not a valid virtual path."
how to solve it??
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Google Image Search" OnClick="Button1_Click" /><br />
<asp:DataList ID="dlSearch" runat="server" RepeatColumns="6" CellPadding="5">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("Url") %>'>
<asp:Image ID="img1" src='<%#Eval("Url") %>' width="200" height="100px" runat="server" />
</asp:HyperLink>
<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Url") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
<br />
</ItemTemplate>
<FooterTemplate>
<asp:Label Visible='<%#bool.Parse((dlSearch.Items.Count==0).ToString())%>' runat="server"
ID="lblNoRecord" Text="No Record Found!"></asp:Label>
</FooterTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Google.API.Search;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
public partial class ImageSearch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dlSearch.DataSource = null;
dlSearch.DataBind();
TextBox1.Text = "";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Title", typeof(string)));
dt.Columns.Add(new DataColumn("OriginalContextUrl", typeof(string)));
dt.Columns.Add(new DataColumn("Url", typeof(string)));
GimageSearchClient client = new GimageSearchClient("www.Google.com");
IList<IImageResult> results = client.Search(TextBox1.Text, 30);
foreach (IImageResult result in results)
{
DataRow dr = dt.NewRow();
dr["Title"] = result.Title.ToString();
dr["OriginalContextUrl"] = result.OriginalContextUrl;
dr["Url"] = result.Url;
dt.Rows.Add(dr);
}
dlSearch.DataSource = dt;
dlSearch.DataBind();
}
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
}
As far as I know there is know way to get file name for online resource like image (if the image hosting provider provides API then that will give you the name other wise not possible). So what you can do is you can generate the name from the url randomly.
So in general all the URL contains the image name at the end. so you can use the String methods to get the image name and then set that as the your filename.
EX:-
string url = #"http://www.hdwallpapersinn.com/wp-content/uploads/2014/07/mumbai-india-desktop-wallpaper-660x330.jpg";
string fileName = String.Join(string.Empty,url.Substring(url.LastIndexOf('/')+1).Split('-'));
and then use it in your response
Response.AppendHeader("Content-Disposition", "attachment; filename=" fileName);
UPDATE
To provide the download from your side you can do as you need to get the image data from the url and then write to the response stream.
WebClient client = new WebClient();
byte[] imageData = client.DownloadData(yourimageurl);
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" fileName);
Response.ContentType = "image/JPEG";
Response.OutputStream.Write(imageData, 0, imageData.Length);
Response.End();
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>
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;