click event of a button to fire fileupload control in asp.net - c#

I have a file upload Control and I have made this invisible.
I want to enable a browse Button for that file upload control when I click another Button.
How can I do it?

First make a file up loader like this one
To upload a file you need to do 2 things
1) Select the file. (click browse button)
2) Send it to server. (click the upload button)
So first lets write a java-script to do these.`
<script type="text/javascript" >
function uploadImage() {
$('#MainContent_UploadButton').click()
}
function selectFile() {
$('#MainContent_FileUploadControl').click();
}
</script>
Now make the file upload controller upload itself as soon as a file is selected
<asp:FileUpload id="MainContent_FileUploadControl" runat="server"
onChange="uploadImage()" class="hidden"/>
Then make a new button and let it select the file as soon as it is clicked.
<asp:Button ID="MainContent_UploadButton" runat="server" Text="Upload File"
OnClientClick="selectFile(); return false;" />
The most important point is put "return false" in the onClientClick field. It will block the buttons post back and let you choose a file without refreshing the page.
Now hide the unwanted components using css and you are done !!

I think this is not possible. This would likely be a security issue if a script could upload (or at least trigger the upload process) invisible from any user interaction.
Update:
Seems that someone actually developed a solution to hide the upload control. From what I read it seems to take some effort to develop and uses JavaScript.
Personally, I wouldn't dare to guarantee that this works on all platforms (just imagine someone with a BlackBerry or Windows Phone visits your website...) and thus avoid it.

<asp:FileUpload ID="FileUpload1" runat="server" style="display:none;"/>
<input id="btnFileUpload" type="button" value="Add" runat="server" />
btnFileUpload.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click();");

Related

File downloading on postback

I have an anchor tag, an AsyncFileUpload control, and a span. The anchor tag's InnerText is set when a file exists in the database, if not, it is hidden. It also has a ServerClick event which downloads the file.
The span tag's InnerText displays the filename of the file uploaded using the AsyncFileUpload OnUploadedComplete.
When I click on the anchor, the file downloads (which is good.) But when I change the file (using the AsyncFileUpload) it posts back and the ServerClick method of the anchor tag is fired again therefore downloading the file again.
<a id="lnkDownloadFile" runat="server"></a>
<span id="spnFilename" runat="server"></span>
<input type="button" id="btnReplaceFile" value="Replace File" runat="server" />
<div>
<ajaxToolkit:AsyncFileUpload ID="fuFile" runat="server" OnUploadedComplete="UploadComplete" OnClientUploadError="UploadError" />
</div>
Is there any way around this?
Thank you.
I am not sure why this is happening but one of the work-around could be to use hidden field to confirm if post-back has happened due to click on download link. For example,
<input type="hidden" id="downloadFile" runat="server" />
<asp:LinkButton id="lnkDownloadFile" runat="server" OnClientClick="return setDownloadFile();" />
<script type="text/java-script" >
function setDownloadFile() {
document.getElementById('<%= downloadFile.ClientID>').value = 'true';
return true;
}
</script>
You can check downloadFile value in the link button click to decide whether to download file or not. Note that I have used LinkButton because I am sure about its client click attribute - you can try use click attribute with html anchor (what I am not 100% sure if it would interfare with ServerClick event handler).

Relay click to Button to trigger ASP.NET File Upload

In a ASP.NET C# website I have an input that uploads a file to my server. To overcome the issue of not being able to style an input of the type=file I have created a styled div that looks like the input but actually just relays the message to the actual input which has display: none to be invisible.
My Problem: Relaying the message isn't working, ie, when I relay the click message to the actual input the file is never uploaded(nothing happens). I know the button works because if I click the actual input it uploads the file sucessfully.
Is there some ASP.NET security stopping me from being able to do this? Whats going wrong? How can I acheive what I am trying to do:
Have a style input where type=file(not a boring browse button) & relay the click to the actual input?
My actual input which works:
<input id="fileUpload" type="file" Runat="server" NAME="fileUpload"/>
<asp:button id="btnSave" OnClick="bt1Clicked"
runat="server" Text="Upload File"></asp:button>
<asp:label id="lblMessage" runat="server"></asp:label>
My styled button:
<a onclick="$(\'btnSave\').click(); return false;" href="#">test</a>
Not sure what your aiming at but this should work
<a onclick="$('<%= btnSave.ClientID %>').click(); return false;"
href="#">test</a>
Why? Because by default, asp.net gives controls its own id, which is defined by ClientIdMode. See also System.Web.UI.Control.ClientID
In my humble opinion, this would be a neater solution:
<a id="btnRelay" href="#">test</a>
Hook it up with JQuery separately, so your code isn't mangled with your html.
$('btnRelay').click(function(event){
event.preventDefault();
$('<%= btnSave.ClientID %>').click()
}

Upload a file to server automatically inside a update panel in asp.net website

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

ASP.NET and C# FileUpload

I have a asp file upload for pictures and what I want to do is, when the file chosen has the same name as the previous file it should pop something up that says "This image name already exists, do you want to replace it? if yes then it would just override the current picture with the new one but if not then just leave it alone. How can I do this?. Right now I have this. Also if the solution is in javascript I could also use that (but i am not too good with javascript :) ) Thank you
<div class="style">
Choose an Image: <asp:FileUpload ID="getImage" runat="server" Width="150px" BorderStyle="Inset" EnableViewState="true" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator"
runat="server" ControlToValidate="getImage" CssClass="Error" Display="dynamic" ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])" ErrorMessage="Select a correct file format"></asp:RegularExpressionValidator>
</div>
Please be aware I am a total newbie with Javascript so if that is what's going to work please explain as if I was a 5 year old.
I really appreciate the help.
My solution will perform the check just before postback. I also use jquery a little bit.
The important piece of the puzzle here is retrieving the previous file name. I created a PageMethod to do this part. So in my aspx.cs file I have a function that looks like this:
using System.Web.Services;
.......
[WebMethod()]
public static string GetPreviousFileName()
{
//put logic here to get the filename to compare against.
return "somefilename.ext";
}
You'll need to implement your own logic for how to retrieve the file name. Another, simpler but less flexible, approach for handling the previous file name would be to add an asp:hiddenfield to your page and populate it with the name of the previous file on page load. Then you could compare by reading $('#<%= hiddenField.ClientID %>').val().
Next I used the following code for my file upload control and a submit buton:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
<div>
<asp:FileUpload ID="fu" runat="server" />
<asp:Button ID="btnUpload" runat="server" OnClientClick="return checkDuplicateFile();" Text="Upload File" />
</div>
Two important things to note here: The ScriptManager has EnablePageMethods="true" and the asp:button has an OnClientClick attribute specified. Lastly, the javascript part of the solution which retrieves the value from the page method and and compares the file names:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var oFilename = "";
$(function () {
//get original file name on page load
PageMethods.GetPreviousFileName(function (result) {
oFilename = result;
});
});
function checkDuplicateFile() {
var newVal = $('#<%=fu.ClientID %>').val();
var newValFile = newVal.substr(newVal.lastIndexOf("\\") + 1);
//returning true causes postback, returning false stops postback.
if (newValFile == oFilename) { return confirm("This image name already exists, do you want to replace it?"); }
else return true;
}
</script>
Couple of things going on here. We use our pagemethod to pull in our old filename from the page method on page load (PageMethods.GetPreviousFileName). Next we setup the function which will be called by our buttons onClick event (client side). The <%=fu.ClientID %> snippet of code will output the client side id of the file upload control for use in our javascript. I do a substring on the file path and extract the file name by pulling back only the text after the last '\' and do the compare.
As my comment in the function says, returning true/false from a function called in the OnClientclick event determines whether a post back occurs. So if the user clicks yes in the confirmation box then a postback occurs, else if they click no then none occurs.
Hope that at least gets you going in the right direction.
Add the code below to your submit button
OnClientClick="return confirm('Are you sure you want to delete this file?')"
Edit as someone pointed out this will ask this question without taking in concern previous file and new one. It will do basic job.
My question is whether you doing this for edit mode or in new item mode. I mean are you editing item or adding new one on page you are interested to check?

FileUpload Status Indicator ASP.Net C#

There are other similar posts, but they all want a progress bar. I don't care.
I will probably end up buying Ajax Uploader, but I would like to know if there is a way to just let the user know if a file is in the process of being uploaded. I have tried an Ajax ProgressIndicator but it doesn't work...The file upload part works, but the progresscontent does not get displayed.
Here is what I have without the Ajax:
<asp:FileUpload onchange="clickTheButton();" ID="FileUpload1" runat="server" />
<asp:Button ForeColor="#ffffff" BackColor="#ffffff" BorderColor="#ffffff" BorderWidth="0"
ID="Button1" runat="server" Text="Add Image" OnClick="AddImage_Click" />
Just a file upload control and a button that uploads the file.
All I need is a way to let the user know that it is busy sending the file.
Why not just create some hidden element on the page like this:
<div id="loadingDiv" style="display: none;">Please wait, uploading file...</div>
and then in the OnClientClick of your upload button, return a function like so:
function displayWaitingMessage(){
document.getElementById('loadingDiv').style.display = 'block';
return true;
}
Should display the message and then proceed with the postback to upload the file.
Just query your server at reasonable intervals with Ajax to see if the file you're trying to upload exists yet, and show an appropriate indication based on the response.

Categories