I am using this code on button click from which I can download a file with a specific name.
But I want, when the user has uploaded a file, in his details like any Id proof details file.
Now to verify the user admin want to see the his Id proof details.
So he will download the file which user had uploaded and that is saved in database.
So the file can be in any type or extension.
private void Button1_click(object sender, System.EventArgs e)
{
string filename="C:\myuploads\invoice.pdf";
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment;" + filename +);
Response.TransmitFile(Server.MapPath(filename));
Response.End();
}
I think this is what you're after.
private void DownloadFile(string file)
{
var fi = new FileInfo(file);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename="+ fi.Name);
Response.WriteFile(file);
Response.End();
}
So you just call it like this:
string myfile = #"c:\path\To\Files\myFile.pdf"; //this wouldn't be a static string in your code
DownloadFile(myfile);
Thanks for answering my questions. My LinkButton to downloading the file from database on particular user Id worked Successfully.
Actually My Download Link was in update panel so It needs the "Trigger" for this.. And My Link was in GridView So I had Passed the Link Button Id in Trigger.
Whenever we use GridView in Update Panel and There is a LinkButton to Download the File from database on particular user Id. We Should Pass **GridView Id not the LinkButton Id in Template Field.**
<asp:UpdatePanel ID="upd" runat="server">
<ContentTemplate>
<asp:GridView ID="grd_UserList" runat="server" CssClass="table"
DataKeyNames="Uid" AutoGenerateColumns="false" AllowPaging="false">
<asp:TemplateField HeaderText="Task Name">
<ItemTemplate>
<asp:LinkButton Id="LinkDownload" runat="Server" CommandArgument='<%# Eval("Attachment") %>' >
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="grd_UserList" />
</Triggers>
</asp:UpdatePanel>
When the user uploads the file, you should be able to use the ContentType property of the posted file. This is assuming you used a file upload control like:
<asp:FileUpload ID="uploadFile" runat="server" />
When the file is uploaded, get the content type using
string fileType = uploadFile.PostedFile.ContentType
Save that value in your DB, and use it as the value of Reponse.ContentType in your existing code, when you download it later.
Related
With HTML5 and ASP.NET 4.5, I created a page that will allow the user to upload multiple files. The ASPX code looks like:
<asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true" />
<asp:Button runat="server" ID="uploadedFile" Text="Upload" OnClick="uploadFile_Click" />
<asp:Label ID="listofuploadedfiles" runat="server" />`
c# code:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
string fileName = Path.GetFileName(uploadedFile.FileName);
uploadedFile.SaveAs("C:\\Users\\username\\Desktop\\Uploaded\\" + fileName);
listofuploadedfiles.Text += String.Format("{0}<br />", uploadedFile.FileName);
}
}
}
The user selects the files using the FileUpload control and clicks the Upload button and it works great.
My question is: Is is possible to upload files using this method without the user selecting the files? I'd like to have the app always point to a directory on the users hard drive and default to uploading the files in that directory.
The user would see the contents of that directory in a list box and click the upload button or some variation to that.
I don't see any way to add files to the FileUpload control in code.
I have a button like below which in charge of opening an image in top of the ASP.NET application.
<asp:Button
ID="MatrixButton"
runat="server"
Text="Risk Matrix"
CausesValidation="False"
OnClientClick="openImageDoc('Images/RiskMatrixCapitalAllocation.jpg', 'RiskMatrix')"/>
Now I need to have another button to do the same function but this time opens a PDF file
<asp:Button
ID="AnalysisButton"
runat="server"
Text="Risk Analysis"
CausesValidation="False"
OnClientClick="openPDFDoc('PDF/RiskAnalysis.pdf.jpg', 'RiskAnalysis')"/>
Here is the JavaScript:
function openPDFDoc(filePath, titleName) {
var newUrl = baseUrl + filePath;
window.open(newUrl, titleName, 'width=900,height=800,scrollbars=1');
}
You need to remove the extension .jpg from the path.
Replace This:
PDF/RiskAnalysis.pdf.jpg
With This:
PDF/RiskAnalysis.pdf
I am uploading files using asp.net fileupload control , whenever postback occurs due to other field's on the page, selected path in file upload control lost. I'm using multiple file upload control on page for diff. Purpose how to solve this problem? Please help with simple & suitable example dear.
string file = Path.GetFileName(UploadSalesServiceCopy.PostedFile.FileName);
string filepath2 = ConfigurationManager.AppSettings["ServerMapImgPath"].ToString();//.......local drive path via web config
string subPath = filepath2 + file;
bool IsExists = System.IO.Directory.Exists(Server.MapPath(subPath));
if (!IsExists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
if (UploadSalesServiceCopy.HasFile)
{
//UploadSalesServiceCopy.SaveAs(subPath);//PHYSICAL path
UploadSalesServiceCopy.SaveAs(Server.MapPath(subPath));//server path
}
else
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "javascript", "alert('No File Selected.')", true);
}
While clicking on Upload button ...
Your page redirect to Page_load event first , where you set page values .
For that in
page_load(..)
{
if(!IsPostBack)
{
..setpagevalues();
}
}
That main reson...you are getting null path....
Try it..
If you are using asp.net File upload control with update panel.Then the problem is
File upload control is not compatible with partial post back.
<asp:FileUpload ID="fpTest1" runat="server" />
<asp:FileUpload ID="fpTest2" runat="server" />
<asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnActions" runat="server" Text="Other Actions" >
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="test" runat="server" OnClick="test_Click" Text="Upload File" />
You can see that when you click other actions button file upload will have the values.
Put the Post back controls inside the Update Panel and have the file upload controls out
of the update panel.
You simply have to use fileupload with updatepanel and also put ViewStateMode="Enabled" to fileupload.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" ViewStateMode="Enabled"/>
</ContentTemplate>
</asp:UpdatePanel>
I've searched for almost 2 days on the internet to find solution but nothing works yet.
I have 2 user controls on a page. First contains AsyncFileUpload:
<cc1:AsyncFileUpload runat="server" ID="fuExcelUploader" Width="400px"
UploadingBackColor="#CCFFFF" ThrobberID="myThrobber"
CompleteBackColor="#CEF6CE" />
and the second has a gridview with such templatefield with download button(excel file)
<asp:TemplateField HeaderText="Report with errors" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton id="lbError" CommandName="ErrorClick" runat="server" CommandArgument='<%# Eval("Report.Id") %>' ValidationGroup="other2357"><asp:Image ID="imgReport" runat="server"
ImageUrl="~/App_Themes/Default/Images/icons/page_excel.png" ImageAlign="Middle" Visible='<%# Convert.ToInt32(Eval("Report.Id")) > 0 %>' /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
In the RowCommand if e.CommandName = ErrorClicked I have such piece of code for downloading file
Response.Clear();
Response.Buffer = true;
Response.AddHeader(
"Content-Disposition", string.Format("attachment; filename={0}", "Error_report_" + this.ErrorClicked + ".xlsx"));
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats";
// Response.Cache.SetCacheability(HttpCacheability.Private);
Response.BinaryWrite(value); //value is byte[];
Response.End();
It works perfect I can upload files with asyncfileupload then download reports by clicking icons on gridview etc. , but there is one problem.
Whenever I click on download icon on gridview, the download file dialog pops up, I can save/open/cancel but whatever I do, after I try to upload new file with asyncfileupload the same RowCommand event is fired with same 'ErrorClick' CommandName and CommandArgument, so I am getting that window with file to download again (and page is locked). It might be because neither linkbutton nor asyncfileupload refresh whole page (is it the same postback?).
Do you have any idea why the rowcommand is fired during uploading with asyncfileupload control or how to solve that problem. I don't use udpatepanels in this case.
The OnRowComand event is fired when you click the Linkbutton and after processing the upload. An error occurs by registering twice the download code.
The script of the "href" in the LinkButton somehow influences this result. I used a ImageButton to trigger the download, and the LinkButton to execute the event click of ImageButton.
ASPX
the ImageButton -> Style="display: none;"
ASPX.CS - RowDataBound
LinkButton.Attributes.Add("OnClick", "$(document.getElementById('" + ImageButton.ClientID + "')).click(); return false;");
Sorry, my English is horrible. I use google Translate.
I have uploaded files to the server using AsyncFileUpload. How can I display the existing files from the folder using asp.net web forms.? I would like to provide a link to the word document to open the file or save it. I couldn't find any example online. Please let me know. Thanks.
Sample code:
Markup:
<asp:gridView runat="server" id="grid" >
<columns>
<asp:HyperLinkColumn DataTextField="Name" DataNavigateUrlField='<%#Eval(Server.MapPath("FullName")) %>' Target="_blank" />
</columns>
</asp:GridView>
Code behind:
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("YourDirectory"));
FileInfo [] files = dirInfo.GetFiles();
grid.DataSource=files;
grid.DataBind();
You would need to simply get the list of files in that directory using Directory.GetFiles (http://msdn.microsoft.com/en-us/library/07wt70x2.aspx) and then display a suitable list using a gridview or repeater etc.