I have an Image control which is used to display image on click of a button. The code is as below:
.aspx code
<asp:Image ID="imgCorrect" runat="server" Height="175px" Width="150px" ImageUrl="~/_layouts/images/NoPreviewShareHR_Grey.jpg" />
<asp:FileUpload ID="FlUpldImage" runat="server" Width="200px" />
<asp:RegularExpressionValidator runat="server" ID="valUp" ControlToValidate="FlUpldImage"
ErrorMessage="Image Files Only (.jpg, .bmp, .png, .gif)" ValidationGroup="ImageFormat"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.jpeg|.JPEG|.bmp|.BMP|.png|.PNG)$" />
<asp:Button ID="btnImageUpload" runat="server" Text="Preview" OnClick="btnImageUpload_Click" CausesValidation="false"/>
<asp:HiddenField ID="HidnLocalImageURL" runat="server" Value=""/>
C# Code
protected void btnImageUpload_Click(object sender, EventArgs e)
{
String fileToUpload = Convert.ToString(FlUpldImage.PostedFile.FileName);
HidnLocalImageURL.Value = fileToUpload;
if (fileToUpload != "")
imgCorrect.ImageUrl = fileToUpload;
else
imgCorrect.ImageUrl = "~/_layouts/images/NoPrview.jpg";
}
The above code works fine on IE but gives issue in Mozilla Firefox:
The RE validator for file upload shows error message as invalid image even if proper
image is selected and
onclick of btnImageUpload the image control disappears. This
issue occurs on Firefox browser only and works fine in IE.
fileToUpload in C# code contains the prope path to the image including drive letter. I don't want to physically store the files into application folder as this is just to preview the image.
Kindly help me to sort out both issues.
Try to log FlUpldImage.PostedFile.FileName.
I think firefox sends only filename not full path.
If so, its better to use simple textbox and paste path in it without dialogbox.
As a security precaution, references to images on your local computer from a remote web site are disabled. If you encounter this restriction and you understand the security implications, you can disable this security measure.
for more info
http://kb.mozillazine.org/Images_or_animations_don%27t_load
Related
I'm using ajaxfileupload right now. After uploading a file with ajaxfileupload, I want to save it to D:folder with saveas.
I use C# and asp.net.I use aspx and aspx.cs. Ajaxfileupload is in ajaxtoolkit in asp.net.
When I saveas with ajaxfileupload, it is indeed saved to a folder. But I can't open it. The file seems to be corrupted. Actually, it is to upload JPG, but when I tried uploading Word and PowePoint, it also broke.
The JPG remains corrupted, but Word and PowerPoint can choose to repair and let the file show its contents. Why can't I get the jpg to be displayed, and doing saveas with ajaxfileupload corrupts all the files? Does AjaxFileUpload destroy everything?
I'm afraid I'm about to be broken by ajaxfileupload until then...Please help me.
The file should be saved just fine. Remember any web based URL will map to a sub folder inside of your root project.
In other words, with code behind, you can as a general rule save the file to ANY location on the computer. However, that will NOT allow web based URL's to map and directly use such files.
So, your web site folders should look like this:
So, add, or create folder - but it in most cases should be inside of the root folder of your web site (it does not have to be).
So, now lets drop in our ajaxfile up, and let the user up-load some files.
Say, this markup:
<div style="width:35%">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnUploadComplete="AjaxFileUpload1_UploadComplete"
OnClientUploadCompleteAll="clickdone" />
</div>
<script>
function clickdone() {
$('#cmdDone').click();
}
</script>
<asp:Button ID="cmdDone" runat="server" Text="Done upload"
OnClick="cmdDone_Click" ClientIDMode="Static" CssClass="btn"/>
Note VERY close in above. We dropped in a button, and we CLICK this button after all files are up-loaded. The ajax fileupload does NOT do a post-back after we are done up-loading the files. (and we want/need a final post-back of the page).
So, I added a ".click()" to the file upload with this:
OnClientUploadCompleteAll="clickdone()"
That simple clicks on our button.
Ok, now we need/want to display the files after the up-load.
so, right below above markup, I dropped in a grid view, but with dispay:none, it will be hidden until all files are done.
So we have this gridview:
<div id="myfiles" runat="server" style="width: 45%; display: none">
<asp:GridView ID="GridFiles" runat="server"
AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" CssClass="table">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:BoundField DataField="UpLoadTime" HeaderText="UpLoaded" />
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="140px"
ImageUrl='<%# Eval("SavePath") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" CssClass="btn" OnClick="cmdDownLoad_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And we have a table like this:
So, we now have this - we select some files:
And after we hit up-load, we see/get this:
Ok, so now all we need is the one up-load "one file" event for the ajax file upload, and that code is this:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
// save file to up-loads folder
string strSaveFile = Server.MapPath(#"~/UpLoadFiles/" + e.FileName);
string strURL = #"~/UpLoadFiles/" + e.FileName;
AjaxFileUpload1.SaveAs(strSaveFile);
// now add this row to data base
string strSQL = "INSERT INTO MyUpLoadFiles (FileName, Size, UpLoadTime, User_ID, SavePath) " +
"VALUES (#FileName, #Size, #UpLoadTime, #User_ID, #SavePath)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#FileName", SqlDbType.NVarChar).Value = e.FileName;
cmdSQL.Parameters.Add("#Size", SqlDbType.Int).Value = e.FileSize;
cmdSQL.Parameters.Add("#UpLoadTime", SqlDbType.DateTime).Value = DateTime.Now;
cmdSQL.Parameters.Add("User_ID", SqlDbType.Int).Value = Session["User_ID"];
cmdSQL.Parameters.Add("#SavePath", SqlDbType.NVarChar).Value = strURL;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
And our button click (that fires after up-load) is this:
protected void cmdDone_Click(object sender, EventArgs e)
{
myuploader.Style.Add("display", "none"); // hide up-loader
myfiles.Style.Add("display", "normal"); // show my files grid
GridFiles.DataSource = MyRst("SELECT * FROM MyUpLoadFiles ORDER BY UpLoadTime DESC");
GridFiles.DataBind();
}
Once this is working, then we can (should) hide that button - since after up-loading, we don't want the user to have to click that "done" button to display the files.
And in the gridview, the download button can look like this:
protected void cmdDownLoad_Click(object sender, EventArgs e)
{
Button myBut = sender as Button;
GridViewRow gRow = myBut.NamingContainer as GridViewRow;
string strFileOnly = gRow.Cells[0].Text;
string strFile = "";
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
string sMineType = MimeMapping.GetMimeMapping(strFileOnly);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileOnly);
Response.TransmitFile(strFile);
Response.End();
}
Now, you have to decide "where" you going to save those files. If you save into a folder OUTSIDE of the web folders, then you cannot use a simple "url" for the file name to download as I did. You can STILL do this, and often this setup is desirable, since when the folder is OUTSIDE of the web folders, then no valid URL's directly mapped to the file(s) exists, and this is VERY good for security. But, then that means the download button, and even display/preview of the files has to be done in a different way (you have to stream the files, and you can use transmit file as I did, but the path names will be different. And if you want a preview in the grid, you ALSO have to stream the file to that image control.
So VERY much keep in mind:
URL - for web and markup = valid path name based on realative to the web site.
Code behind: ALWAYS will use a plane jane full windows path name. So, you have to be aware of this difference in how web based URL's work with a file as opposed to code behind which ALWAYS will use a plane jane full windows path name.
As for file corruption? No, I am not seeing nor experiencing this. You might want to edit your answer, and show your save code for the file up-load event you have. You don't show how you are downloading the file. I suppose you could open that MyUpLoadFiles folder directly, and see if the file is corrupter, but I not experience that issue.
I have created an image folder in my root project folder
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
I am linking my images here:
if (dropDownList.SelectedItem.Value == "Picture 1")
{
Image1.ImageUrl = "~/images/picture1.jpg"
}
When I visit the web page I get a small img box with an x instead of my image.
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
is setting the url to a directory (folder), not an image. That's why you're getting the small image-box and not an image.
If you want an image to show up when the page loads, set it to a valid image:
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
This line of code is setting an invalid image url as it only contains the folder path. So in your code you must ensure that you override the Image1's ImageUrl property to valid image file. Based on your requirement here is something you can do.
In aspx page, set the image url to picture1.jpg assuming that option1 is selected by default in the dropdown so picture1.jpg will be displayed on initial page load.
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
Next, set the AutoPostBack property of your dropdown to true so that image source code can be updated dynamically based on dropdown selected value
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
In selectedIndexChanged event handler update image source based on the selectedItem
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Image1.ImageUrl = "~/images/" + DropDownList1.SelectedItem.Value;
}
Hope this helps
It was displaying the small image box with X as it was not able to find the image at the path specified.
So, Add you images folder in wwwroot folder instead of Project root.
After that you can use <asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
for rest you can follow Mohsin's answer
Try to use .Scr instead of ImageUrl.
I have a webpage in which I am trying to hyperlink an image. The screenshot of that section of the webpage is as follows:
On clicking the pdf image, it should open a pdf.
At this moment, I am able to create a pdf image which is local to my machine.
The code in .aspx file are:
<div class="row" id="divViewAssessment" runat="server">
<div class="itemtitle">
<asp:Label ID="litBlankAssessment" runat="server"></asp:Label>
</div>
<div class="itemdata">
<asp:ImageButton ID="btnViewAssessment" runat="server" ImageUrl="~/Images/doc_pdf.gif"
CausesValidation="False" ValidationGroup="vgrp1" Enabled="true"></asp:ImageButton>
</div>
</div>
I am wondering what code do I need to put in .aspx.vb file ? I am sure what I need to put in .aspx but not sure what need to put in .aspx.vb (behind the code).
The path of the pdf local to my machine is "~/Licensee/" + CStr(Session("LicenseeCode")) + "/ViewSA/Lebanon Primary Care Standards for SW.pdf" The LicenseeCode is MPHLB.
The ImageButton control is intended for triggering a postback, not navigating to a URL.
Use a HyperLink control instead. It has an ImageUrl property to set the image that is displayed, and also a NavigateUrl property to set your target URL.
You can use the following code..
Protected Sub btnViewAssessment_Click(sender As Object, e As ImageClickEventArgs) Handles btnViewAssessment.Click
Response.Redirect("Lebanon Primary Care Standards for SW.pdf")
End Sub
Put your pdf in solution folder.
I have a file upload inside the update panel, and an upload button that uploads the file to the server. Is it possible to upload the file without clicking the upload button? I want to remove the upload button and upload the file as soon as the file is selected from the user's machine. Or, have a 4 second timer, then call the upload_click to check if the fileupload has a file or not. How can I do it without a button inside update panel?
<asp:UpdatePanel ID="UP_DDL" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Upload" OnClick="Upload_Click" runat="server" Text="Upload" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Upload"/>
</Triggers>
</asp:UpdatePanel>
protected void Upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Bulk Upload"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
}
I am sure you can use any of the events on the HTML INPUT File element to fire up a full post back, which is all you need in order to upload the file automatically.
Google, at least on the standard interface, uses some sort of Flash plugin to accomplish what you want.
There might be some other jQuery plugins that provide this functionality out of the box. This one, for example, seems to do it.
You would need to mimic the click with some client-side code, such as using submit from Javascript - and this is not supported by at least one notable browser, I believe, IE.
Otherwise, you could use jQuery ajax calls to static web methods which do uploads on the fly, behind the scenes, when the value of the file upload control have changed.
You can hide Upload button with display:none inline style and add following code to Page_PreRender method:
FileUpload1.Attributes["onchange"] = ClientScript.GetPostBackClientHyperlink(Upload, "");
Or consider to use AsyncFileUpload control from AjaxControlToolkit
i am using WATIN (i am using 2 days...)to get any web site's content like that:
Deault.aspx:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="some_textbox" runat="server"> </asp:TextBox>
<asp:Button ID="submit_button" runat="server" Text="search"
onclick="submit_button_Click" />
<asp:Label ID="lblMsg" runat="server" Text="" ></asp:Label>
</div>
</form>
</body>
My Client Codes via Watin(http://watin.org/documentation/getting-started/)
private void button1_Click(object sender, EventArgs e)
{
//launch a new IE browser
using (FireFox browser = new FireFox("http://localhost:3411/Default.aspx"))
{
//now we have access to the browser object
//filling a textbox and clicking a button is as easy as
browser.TextField(Find.ByName("some_textbox")).TypeText("foobar");
browser.Button(Find.ByName("submit_button")).Click();
//we can also access the full html of the page to perform regex matches, scrapes, etc...
string fullPageSource = browser.Html;
}
}
i have 2 question:
1) i dislike to open in web browser it must be run back ground. because i will searh some data in 20-30 pages one event. PLease don't monitor me web pages every thing must run back ground
2) i am writing textbox name button name or whatelse. i don't have any idea textboxname or search button name because i will search some product in amazon.
i need some trick how to make a price comparison like http://www.pricegrabber.com/ WATIN is good idea or do you have any httprequest dll or method?
Watin is designed to drive the web browser in the same way that a user would. If you don't want to open a web browser, neither Watin nor Watir is an effective solution to what you want to do. (legality issues aside).
You'll probably want to use some other means to make HTTP requests and then parse through the returned HTML, once that is you've gotten written permission from Amazon to access their site with a data gathering tool, since doing so without the permission is against their conditions of use.