I can't figure out how to upload a file using the upload button and then insert into (along with other stuff) the database.
When I debug into btnRegister_Click, HasFile returns false.
Is there a way to persist HasFile across 2 different button onclicks?
Upload code:
<tr>
<td>Expense Receipt
</td>
<td class="blackDisplayName">
<asp:UpdatePanel ID="uplExpenseReceipt" runat="server" ViewStateMode="Enabled">
<ContentTemplate>
<asp:FileUpload ID="fuExpenseReceipt" runat="server" />
<asp:Button ID="btnUploadExpenseReceipt" runat="server" Text="Upload" OnClick="btnExpenseReceiptUpload_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUploadExpenseReceipt" />
</Triggers>
</asp:UpdatePanel>
<asp:Label ID="lblFileWarning" runat="server" Text="" Font-Bold="true" ForeColor="Red"></asp:Label>
</td>
</tr>
C# code behind:
protected void btnExpenseReceiptUpload_Click(object sender, EventArgs e)
{
if (!fuExpenseReceipt.HasFile)
{
lblFileWarning.Text = "Please browse your computer to load a pdf or jpg file";
return;
}
if (fuExpenseReceipt.PostedFile.ContentLength > 1000000)
{
lblFileWarning.Text = "file size must be < 1Mb";
return;
}
//if (!fuExpenseReceipt.PostedFile.ContentType.Equals("application/pdf") | !fuExpenseReceipt.PostedFile.ContentType.Equals("image/jpg"))
if (!fuExpenseReceipt.PostedFile.ContentType.Equals("application/pdf"))
{
lblFileWarning.Text = "Only pdf or jpg files are allowed to be uploaded";
return;
}
if (!Directory.Exists(#"C:\Ireland Resources\ExpenseReceipts"))
{
Directory.CreateDirectory(#"C:\Ireland Resources\ExpenseReceipts");
}
string FolderUpload = #"C:\Ireland Resources\ExpenseReceipts\";
string PostedFile = FolderUpload + User.Identity.Name + "-" + fuExpenseReceipt.PostedFile.FileName;
fuExpenseReceipt.SaveAs(PostedFile);
}
Register code:
<td class="blackDisplayName" align="right">
<asp:Button ID="btnRegister" runat="server" Text="Register" ValidationGroup="ExpenseRegistration"
OnClick="btnRegister_Click" CssClass="gray-gradient" SkinID="NONE"/>
</td>
C# code behind:
protected void btnRegister_Click(object sender, EventArgs e)
{
try
{
if (!fuExpenseReceipt.HasFile)
{
lblFileWarning.Text = "Please browse your computer to load a pdf or jpg file";
return;
}
byte[] expenseReceipt = null;
Stream fs = fuExpenseReceipt.PostedFile.InputStream;
byte[] bytFileData = new byte[fs.Length];
fs.Read(bytFileData, 0, Convert.ToInt32(fs.Length));
fs.Close();
expenseReceipt = bytFileData;
int tillID = Int32.Parse(hfTillID.Value);
double beforeVAT = double.Parse(txtBeforeVAT.Text);
double VAT = double.Parse(txtVAT.Text);
double totalAmount = double.Parse(txtExpenseTotal.Text);
lblExpenseMessage.Visible = true;
try
{
new TillEndOfDayDAL().SaveExpense(StationID, tillID, beforeVAT, VAT, totalAmount, txtExpenseDescription.Text
, expenseReceipt, Int32.Parse(ddlExpenseTypes.SelectedValue), Page.User.Identity.Name.ToUpper());
lblExpenseMessage.Text = "Sundry expense has been successfully registered.";
}
I resolved the issue by doing the following:
Removed the Upload button
Moved the PostBackTrigger to the end of the 'outer' UpdatePanel, which contains both the FileUpload Control and Register button.
Changed the PostBackTrigger ControlID to the Register button.
Related
I have this Asp.net code:
<asp:Panel ID="pnlCustomer" runat="server">
<p class=".SmallCaption">
<b>Edit report</b></p>
<table class="DataTable" id="Bug" cellspacing="0" cellpadding="2" width="100%" border="0">
<tr>
<td class="CellName" width="25%">
<asp:Label CssClass="CasualForm" id="lblUploadFile" runat="server">Save new file</asp:Label>
</td>
<td class="CellValue" width="25%">
<asp:FileUpload CssClass="formdata100" ID="fuUploadedFile" runat="server" />
</td>
<td class="CellName" width="50%" colspan="2"> </td>
</tr>
<tr>
<td class="CellName" width="25%">
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="BtnDeleteReport" style="float:left" OnClientClick="if(confirm('Do you really want to delete this report?')) {this.disabled = true;} else {return false;}" UseSubmitBehavior="false" />
</td>
<td class="CellName" width="25%"> </td>
<td class="CellName" width="47%">
<asp:Button ID="btnDownloadFile" runat="server" Text="Get Report" onclick="btnDownloadFile_Click" />
</td>
<td class="CellName" width="3%">
<asp:Button ID="btnSave" runat="server" Text="Edit" OnClientClick="if(checkFileUploadSize()) {return true;}" onclick="btnEdit_Click" CommandArgument="Edit" />
</td>
</tr>
</table>
</asp:Panel>
and this is backcode C#:
protected void btnEdit_Click(object sender, EventArgs e) {
Button btnThis = (Button) sender;
if (btnThis.Text == "Edit") {
Edit();
btnThis.Text = "Save";
} else if (btnThis.Text == "Save") {
Save();
//btnThis.Text = "Edit";
}
}
private void Save() {
ReadDataFromGUI();
// insert/update report in DB.
int _id = reportsHandler.Update(report);
Response.Redirect("~/ReportsEditor.aspx?id=" + _id);
}
private void ReadDataFromGUI() {
if (report == null)
report = new Support_Report();
report.id = report_id;
report.id_entity = int.Parse(ddlEntities.SelectedValue);
report.inactive = cbInactive.Checked;
report.name = txtName.Text.Trim();
report.description = txtDescription.Text.Trim();
report.report_condition = txtReportCondition.Text.Trim();
int _so;
isSortOrderInteger = int.TryParse(txtSortOrder.Text.Trim(), out _so);
if (isSortOrderInteger) {
report.sort_order = _so;
}
string StrFileName = Path.GetFileName(fuUploadedFile.FileName);
int IntFileSize = fuUploadedFile.PostedFile.ContentLength;
if (StrFileName != null && StrFileName != "") {
string path = Utility.Utility.GenerateTempFileName(StrFileName);
FileInfo fi = new FileInfo(path);
fuUploadedFile.PostedFile.SaveAs(path);
try {
var extension = Path.GetExtension(StrFileName).Replace(".", "");
report.report_type = extension;
if (extension == "mrt") {
var xml_doc = new XmlDocument();
xml_doc.Load(path);
report.report_file = xml_doc.OuterXml;
} else {
report.report_file = Convert.ToBase64String(File.ReadAllBytes(path));
}
} finally {
fi.Delete();
}
}
}
When I insert a file and want it to upload it looks like this: Before
But when I press the "save" button then that file is deleted on the page and refreshed the page. Still, that file is in the database but I can't see it on that page. Then it looks like this after saving: After Why is this happening? How to fix that it always shows me even after the update?
The file upload control can ONLY survie ONE post back. When you click on ANY button that causes a post-back, then the file upload REALLY starts. And once that is done, then your code has to grab + save that information about the file. When code behind is now done, the file-upload control is re-set, and the file can no longer be had, looked at, or used by the upload control.
And I not really sure of the logic of having a "edit" button. Why not just have a single save or submit button. I mean, some edit button not going to always be hit by the user - they will just start typing into the text boxes, and then hit save. But as noted, any button click (post-back) will cause the up-load to start, and then as noted, in that post back you have ONE chance to get that information.
With the introduciton fo a edit button, then a user might use the file upload to select a file, then say hit edit - that's going to trigger the post-back.
As a result, you need ONE save button to de-confuse the UI, but more important, on that save, you have to save that file, update your database, and in fact probably want to either hide the up-load control, or move on in your UI from the up-loader page to some other display of the information. So, you want user to enter information, select a file, and then hit ONE button to start the up-load, and then save the information entered. If you allow additonal files to be up-loaded, then want to save/setup some hidden field, or some such to keep track of that issue.
I am trying to show an image on website after choosing it and then saving it to database.
C# .aspx
<td ><strong>Product Photograph</strong></td>
<td ><asp:FileUpload runat="server" ID="FileUpload1"/>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<asp:Image ID="Image1" runat="server" />
</td>
c#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "~/Images/" + fileName));
}}
}
How to attach choosen image with ID="Image1" i don't know.Any help would be appreciated.
This may help you to read image from file and bind in asp:Image control
Image1.ImageUrl= "data:image/jpg;base64," + Convert.ToBase64String(File.ReadAllBytes(fileName));
I have a webs form page and I have a text box which once clicked passes a variable to the code behind and then back into another element of that page and I cannot get it to work.
This is the closest I have got.
<asp:Panel ID="Search" runat="server" Visible="true">
<tr>
<td>
<asp:Label ID="lblSearch" runat="server" Text="Search"></asp:Label>
</td>
<td>
<asp:TextBox ID="search" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="valSearch" runat="server"
ControlToValidate="movieSearch" Text="Please enter text" />
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Save"
OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel ID="pnlSearchResult" runat="server" Visible="false">
<script>
var search = '<%=Server.UrlDecode(Request.QueryString["Data"]) %>';
</script>
</asp:Panel>
And the code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
pnlSearch.Visible = false;
pnlSearchResult.Visible = true;
Response.Redirect("search.aspx?Data=" + Server.UrlEncode(search.Text));
}
}
Also this does not change the visibility of the two panels for some reason.
I would appreciate any guidance I am very new to asp and c#.
The panel's visibility is not changing because you're forcing a new GET request to the page with this: -
Response.Redirect("search.aspx?Data=" + Server.UrlEncode(search.Text));
(I'm assuming your page is called 'search.aspx')
There's no need to do this. Remove this line.
Secondly, I see you want to force the textbox's Text value into a Javascript variable. Replace this
var search = '<%=Server.UrlDecode(Request.QueryString["Data"]) %>';
with this
var search = '<%= search.Text %>';
Write below code on page event.
Another more important point is you first panel Id is "Search" not "pnlSearch" on aspx page so please correct it
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Data"] != null)
{
Search.Visible = false;
pnlSearchResult.Visible = true;
}
}
I recommend solution without using Response.Redirect.
Code Behind Submit Button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
pnlSearch.Visible = false;
pnlSearchResult.Visible = true;
}
}
In Markup:
<asp:Panel ID="pnlSearchResult" runat="server" Visible="false">
<script>
var searchTxt = document.getElementById('search');
if(searchTxt.value != null && searchTxt.value != ''){
//do your stuff
}
</script>
I am trying to create a page that has a variable number of FileUpload fields, depending on the number selected from a drop down list by the user.
my .apsx code is as follows;
<tr>
<td>Number of photo's to upload</td>
<td><asp:DropDownList ID="DLPhotoCount" runat="server" OnSelectedIndexChanged="OnSelectedIndexChanged_PhotoCount" AutoPostBack="true">
<asp:ListItem Text="..."></asp:ListItem>
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td>Picture 1:</td>
<td><asp:FileUpload runat="server" ID="Pic1" Visible="false"/></td>
</tr>
<tr>
<td>Picture 2:</td>
<td><asp:FileUpload runat="server" ID="Pic2" Visible="false"/></td>
</tr>
<tr>
<td><asp:Button runat="server" ID="BtnUploadFiles" text="Upload Files" OnClick="OnClick_BtnUploadFiles" Visible="false"/></td>
</tr>
and my C# is;
protected void OnSelectedIndexChanged_PhotoCount(object sender, EventArgs e)
{
string Pic = "Pic";
int PicNo = Convert.ToInt32(DLPhotoCount.SelectedItem.Text);
if (DLPhotoCount.SelectedItem.Text != "...")
{
string StPicNo = Pic + PicNo;
do
{
FileUpload StPicNo.Visible = true;
PicNo = PicNo + 1;
}
while (PicNo < Convert.ToInt32(DLPhotoCount.SelectedItem.Text + 1));
BtnUploadFiles.Visible = true;
}
else
{
Pic1.Visible = false;
Pic2.Visible = false;
BtnUploadFiles.Visible = false;
}
}
Open to suggestions on any alternatives if this isn't the best way to achieve the required functionality
Its a good practice to create file upload control dynamically based on the value selected from dropdownlist.
Sample examples to add fileupload controls using javascript are available under below links
http://www.aspsnippets.com/Articles/Uploading-Multiple-Files-using-JavaScript-Dynamic-FileUpload-Controls-in-ASP.Net.aspx
http://www.codeproject.com/Articles/24914/Multiple-Dynamic-File-Uploading
The advantage of this is you dont have to do a condition check in code behind file and no code change required if your business requires to add more file upload controls in future.
I am having an Ajax Asynchronous file upload control in update panel. My upload works fine but after the upload is completed., I need to see the image I have uploaded.
But it doesnt work here is what I have done
function UploadComplete(sender, args) {
var filename = args.get_fileName();
var contentType = args.get_contentType();
if (contentType.indexOf('image') == -1) {
document.getElementById('<%=lblStatus.ClientID%>').innerText = "Uploaded file must be an Image!"+ "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
document.getElementById('<%=AsyncFileUpload1.ClientID%>').text.style.backgroundColor = "Red";
}
else {
var text = "" + filename + " | " + args.get_length() + " bytes"+"Uploaded Succesfully";
document.getElementById('<%=lblStatus.ClientID%>').innerText = text;
$get("imageView1").src = "./~/" + filename;
}
}
AspCode:
<ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red" ClientIDMode="AutoID"
ThrobberID="Throbber"
UploadingBackColor="#66CCFF"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<asp:Image runat="server" ID="imgPreview" ImageUrl="~/Images/uploading.gif" />
</asp:Label>
<img runat="server" id="imageView1"/>
<asp:Label ID="lblStatus" runat="server" Style="font-family: Arial; font-size: small;"></asp:Label>
You can use the OnUploadedComplete event to display the image.
<ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server" OnUploadedComplete="ProcessUpload"
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileName = Server.MapPath("./") + "image.jpg";
AsyncFileUpload1.SaveAs(fileName);
ScriptManager.RegisterClientScriptBlock(AsyncFileUpload1, AsyncFileUpload1.GetType(), "img",
"top.document.getElementById('imgUpload').src='image.jpg';",
true);
}
For Details on how to show the preview take a look at this example: AJAX File Upload in ASP.NET with the AsyncFileUpload Control
I don't think "~" will work with HTML controls. Try converting the path to actual path and set the Image src.