Code behind image input in C# - c#

here is my code :
<label for="image" >Image input</label>
<input id="image" type="file" name="pic" accept="image/*">
i don’t know the code behind to get value from the inserted image and save it in my project folder. please help me. thanks in Advance.

If you want to access what is put into the files collection using jScript:
function SaveImage()
{
var uploadFileElement = document.getElementById("image");
var theFile = uploadFileElement.files[0];
// Use AJAX or call a PageMethod to initiate Server Side Processing
// to Save the file
}
Just add a standard html button on your form that calls this function to initiate the saving of your file.
If you want to use standard Server Side (ASP.NET Controls), I would suggest using the FileUpload control.
Put this in your aspx page:
<asp:FileUpload ID="FileUpload_UploadFile" runat="server" />
<asp:Button ID="Button_UploadFile" runat="server" Text="Upload File" onclick="Button_UploadFile_Click" />
Put this in your code behind (.cs):
private void Button_UploadFile_Click(object sender, EventArgs e)
{
if (FileUpload_UploadFile.HasFile)
{
// IMPLEMENT YOUR CODE FOR SAVING THE FILE
}
}

Related

Upload FileUpload

I'm working on a project in which I have to upload .txt files. I'm using asp.net FileUpload. Here is a piece of code:
<div class="custom-file">
<asp:FileUpload ID="inputFileTXT" CssClass="custom-file-input" runat="server" />
<label id="lblFileName" runat="server" class="custom-file-label" for="inputFileTXT">Elegir archivo</label>
</div>``
I'm using styles from MDBootstrap.
The thing is that I want to do stuff when a user clicks on the asp:fileUpload element and selects a file WITHOUT CLICKING ON A BUTTON. I've been searching but I didn't find how to detect dynamically this action. The asp:fileUpload has no event such as OnUploading.
PD: I tried using an UpdatePanel but when it makes the postback it seems like the uploaded file disapears. Maybe this is the way but I couldn't make it work.
You can add a dummy LinkButton to the page and leave it empty, but give it an OnClick, in which you would process the file.
<asp:FileUpload ID="FileUpload1" runat="server" accept="image/*" />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>
Then in code behind add the onchange trigger to the FileUpload control that will do a PostBack of LinkButton1.
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
}
PS do not put a FileUpload Control in an UpdatePanel.
You want to detect when a file is assigned to the upload just use change event.
Jquery solution:
$('#inputFileTXT').on('change', function(){
//do stuff
});
javascript solution:
<asp:FileUpload ID="inputFileTXT" CssClass="custom-file-input" runat="server" onchange="doStuff(this);" />
function doStuff(control){
//do stuff
}
You can then read files by using FileReader api (https://developer.mozilla.org/en-US/docs/Web/API/FileReader).
and access files using .files:
var files = $('#inputFileTxt').files;
Please have a look at this link
You should get the file details in FileUpload1 (fileUpload control Id: inputFileTXT in your case).

Using ASP.NET to Hide an HTML Div

I am using ASP.NET for a web page in order to make some server calls that involve looking up user organization information. Based on that information, we need to either hide or display a div. In the header I have a C# function that definitely runs. I have tried the following lines to hide the div.
divID.Style.Add("display","none");
and
divID.Visible = false;
In the body, I am currently using an asp:Panel that runs at server and contains the id "divID". No matter what I do, I can't get the div to hide (without manually putting the styling in). I tried putting the scripts before and after the body, and it didn't make a difference. Any suggestions on the best way to do this would be appreciated.
EDIT:
Here is the C# initiating code.
<script runat="server" language="C#">
void getUserInfo(Object sender, EventArgs ev){
The rest of the C# code is irrelevant, but the relevant line shown above is definitely being run.
The HTML portion looks something like this.
<asp:Panel runat="server" id="divID" style="width:200px; height:130px; ">
<div style="text-align:center">Test Data</div>
</asp:Panel>
C# code is always compiled and run from the server-side, and so cannot impact the state of a page once rendered unless you use postbacks or callbacks. If you want to change the visible state of a control on the client-side, you will need to use Javascript on the client side (possibly triggered by a button click) to show and hide the control.
As an example, check out the solution at the link below.
https://forums.asp.net/t/1603211.aspx?Show+hide+div+on+button+click+without+postback
<script type="text/javascript">
function ToggleDiv(Flag) {
if (Flag == "first") {
document.getElementById('dvFirstDiv').style.display = 'block';
document.getElementById('dvSecondDiv').style.display = 'none';
}
else {
document.getElementById('dvFirstDiv').style.display = 'none';
document.getElementById('dvSecondDiv').style.display = 'block';
}
}
</script>
<asp:Button ID="btn" runat="server" Text="Show First Div"
OnClientClick="ToggleDiv('first');return false;" />
<asp:Button ID="Button1" runat="server" Text="Show Second Div"
OnClientClick="ToggleDiv('second');return false;" />
<br />
<div id="dvFirstDiv" style="display: none;">
First Div
</div>
<div id="dvSecondDiv" style="display: none;">
Second Div
</div>
In the header I have a C# function that definitely runs.
If you're talking about the HTML page header - no, it definitely not running. C# code is executed only server side.
Based on your post, I'm assuming we're talking WebForms here and yo have a script block in your aspx file. While this is fine, I recommend placing the server-side code into a code behind file.
So all you need to do is to add a handler for the PreRender phase of the page life cycle and place your logic for showing/hiding the div in there.
public void Page_Prerender(object sender, EventArgs e)
{
divID.Visible = false;
' OR
'divID.Style.Add("display","none");
}
Note that setting the Visible property of a WebForms control excludes the control from rendering to the page, whilst setting display: none renders it as HTML but it isn't displayed on the page.
Try in backcode: divID.Controls.clear();
This worked for me.

How to save tinymce using asp button

I'm using asp.net and c# to build a website that can upload,edit,save the file. I have use tinymce as the texteditor but the problem is the I dint know how to configure the save plugins in tinymce..I have add asp button to use as save button but how to configure it to save into file .html?
javascript to replace tiny with texeditor:
$('#<%=btnsave.ClientID%>').show() //save button
tinymce.init({selector: "textarea"}); //replace texteditor
this is markup code:
<textarea name="textarea" cols="100" rows="5" style="visibility: hidden;">
</textarea>
<br /><asp:Button Text="Save" runat="server" ID="btnsave" style="display:none;" onclick="btnsave_Click" />
This in code behind
protected void btnsave_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~/WordExcelPPointToHtml/test.html");
File.WriteAllText(path,HtmlTextArea); //this line have error!!
}
Can anyone help me on this ?. Thanks in advance. Eagerly waiting for answers.
You need to replace the html control with an ASP.NET web control, and they you will be able to access the value programmatically in the code behind.
E.g.
<asp:TextBox ID="txt" Name="textarea" Columns="100" Rows="5" TextMode="MultiLine" runat="Server"></asp:TextBox>
And in the code behind:
protected void btnsave_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~/WordExcelPPointToHtml/test.html");
File.WriteAllText(path, txt.Text);
}
You should also consider some error handling in btnSave_Click

how to upload an image file without any postback in ASP.NET

I am uploading a file using the <asp:FileUpload> and <asp:button> controls but I want to do it without a postback. On button click I execute the following code.
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileName = Path.GetFileName(FileUpload1.FileName); //fileupload1 is the <asp:fileupload ID
FileUpload1.SaveAs(Server.MapPath("~/UploadFile/" + strFileName + ""));
imgUpload.ImageUrl = "../UploadFile/" + strFileName + ""; //imgupload is the <img ID on which I am showing the image after upload
imgUpload.Visible = true;
}
After uploading the file I am showing the saved image from the specified folder in my project solution, but on clicking the upload button the whole page gets loaded and I don't want the postback on clicking the upload button.
just add the script
<script language="javascript">
function Change(obj) {
__doPostBack("<%= btnUpload.ClientID %>", "");
}
</script>
Call the script in your button click event like this
<pre>
onchange="Change(this);"
</pre>
Your image control added in the update panel with contentTemplate
<asp:FileUpload ID="imgFileUploader" runat="server" />
<asp:Button ID="btnUpload" runat="server"
Text="Upload" onclick="btnUpload_Click" onchange="Change(this);" />
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<img id="imgOrginal" runat="server" style="height: 200px; width: 200px;" />
</ContentTemplate>
</asp:UpdatePanel>
for more details
if you are using ASP.Net file uploader then is is not possible.. you can use Ajax file uploader for this purpose
Best way to upload images without any postback, you can try AsyncFileUpload control in Asp.net Ajax. A good example is here :-
http://www.aspsnippets.com/Articles/Using-ASP.Net-AJAX-Control-Toolkits-AsyncFileUpload-Control.aspx
Thankyou
I think you are asking about uploading files through partial request. Using ASP.NET file upload control it is not possible. Even it is wrapped inside update panel, it will not work. It needs to have synchronous trigger to make it work, that means it does full post back.
If you are using ASP.NET AJAX, checkout asyncfileload control and newly added 'Ajax file upload' control. These controls are present in Ajax control tool kit. Please go through the documentation since each have their limitations.
If they doesn't suit your needs, try for open source Ajax file upload controls like neat upload etc.
You can't do this using simple ASP.NET WebForms.
Do some research into what is known as the page lifecycle. Code behind methods like the one you've included are / can be executed only as part of a postback or server-side action.
If you want client-server interaction without a postback then you need to use javascript. You can use javascript alongside ASP.NET, and I believe there is a Microsoft implementation of 'AJAX' in the .NET framework.
You need to use ajax for this purpose. There are plenty of examples available on internet. Just google it.

How to correctly use the ASP.NET FileUpload control

I'm trying to use the FileUpload control in ASP.NET
Here's my current namespace setup:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
And within my class, I'm just using:
FileUpload fileUpload = new FileUpload();
However, none of the attributes that are normally part of FileUpload seem to be available... such as .HasFile. I'm attempting to make the Button click method in the code behind, I have noticed that most of the usage of .HasFile is in the code in front, however it was my understanding that this shouldn't matter.
Does anyone know why?
ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:
<asp:FileUpload ID="FileUpload1" runat="server" />
Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.
Add a button that will do the post back:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
And that's it. All should work as expected.
Instead of instantiating the FileUpload in your code behind file, just declare it in your markup file (.aspx file):
<asp:FileUpload ID="fileUpload" runat="server" />
Then you will be able to access all of the properties of the control, such as HasFile.
Adding a FileUpload control from the code behind should work just fine, where the HasFile property should be available (for instance in your Click event).
If the properties don't appear to be available (either as a compiler error or via intellisense), you probably are referencing a different variable than you think you are.
My solution in code behind was:
System.Web.UI.WebControls.FileUpload fileUpload;
I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.
I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.
The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:
FileUpload fileUpload = new FileUpload();
is not inside a function in your code behind.
Old Question, but still, if it might help someone, here is complete sample
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
<asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="UploadFile" /><br/>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
In your Code-behind, C# code to grab file and save it in Directory
protected void UploadFile(object sender, EventArgs e)
{
//folder path to save uploaded file
string folderPath = Server.MapPath("~/Upload/");
//Check whether Directory (Folder) exists, although we have created, if it si not created this code will check
if (!Directory.Exists(folderPath))
{
//If folder does not exists. Create it.
Directory.CreateDirectory(folderPath);
}
//save file in the specified folder and path
FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));
//once file is uploaded show message to user in label control
Label1.Text = Path.GetFileName(FileUpload1.FileName) + " has been uploaded.";
}
Source: File Upload in ASP.NET (Web-Forms Upload control example)

Categories

Resources