Load Image with Javascript from ASP.NET FileUpload control - c#

I am trying to load an asp image box <asp:Image ID="imgPicture" width="200" height="200" runat="server" /> with an image after a user has selected one using the asp.net fileupload control <asp:FileUpload ID="fluPicture" runat="server" OnChange="LoadImage(this.value, 'imgPicture');" Width="200"/>
HTML
<asp:Image ID="imgPicture" width="200" height="200" runat="server" />
<asp:FileUpload ID="fluPicture" runat="server" OnChange="LoadImage(this.value, 'imgPicture');" Width="200"/>
Javascript
<script type="text/javascript">
function LoadImage(path, img) {
imgPrev = document.images[img];
imgPrev.src = path;
}
</script>
The image will not load in the imgPicture control. Also I noticed that by adding an alert to the javascript function to alert the path and image, that the path is C:\fakepath\ImageName.jpg. I am unsure why it says fakepath.
Any help is appreciated. Also note that this project has a C# code file behind it.

After all of your input, I have changed my FileInput control code to be as follows:
<asp:FileUpload ID="fluPicture" onchange="if (confirm('Upload ' + this.value + '?')) this.form.submit();" runat="server" Width="200"/>
I then added a test to the Page.OnLoad event to determine if the file is ready to be
uploaded.
if (fluPicture.PostedFile != null && fluPicture.PostedFile.ContentLength > 0) UploadImage();
Then I allowed the UploadImage() method to upload the image, store it, and then set the url of the imagebox to the uploaded image's url.
Thank you all for your help and input. Also, I appreciate the jQuery ideas. In this instance I just needed something quick and dirty to get the job done.

You file is not uploaded until you do a post back, it sounds like your only browsing to the file and then trying to get a thumbnail before you post back/upload the image.

ASP.Net (HTML) CODE :
<asp:FileUpload ID="FileUpload1" runat="server" Height="22px" onchange="showImage()"/>
<asp:Image ID="Image1" runat="server" Width="200PX" Height="200PX" />
JAVASCRIPT CODE :
function showImage()
{
// Get File Upload Path & File Name
var file = document.getElementById("FileUpload1");
// Set Image Url from FileUploader Control
document.getElementById("Image1").src = file.value;
// Display Selected File Path & Name
alert("You selected " + file.value);
// Get File Size From Selected File in File Uploader Control
var inputFile = document.getElementById("FileUpload1").files[0].size;
// Displaty Selected File Size
alert("File size: " + inputFile.toString());
}
I think That can Help You. its perfectly run on my pc.

Related

C# How get bitmap from dynamic <img> in code behind in .aspx

I'm using a video tag to capture a screenshot of the video in a web page and put it into an img element. Then I want to post it to the code behind so I can process its bitmap. I'm using an UpdatePanel for the postback. When I run this in a debugger, it captures the image from the video, builds the canvas, draws the image into the element, displays the image correctly, and then calls the Decode function in the code behind. However, the img.src is blank in the code behind Decode function.
<asp:UpdatePanel runat="server" UpdateMode="Conditional" EnablePartialRendering="true"/>
<asp:Button runat="server" AutoPostBack="true" OnClientClick="return screenshotButton()" OnClick="Decode" Text="Capture"></asp:Button>
<canvas id="theCanvas" style="display: none;"></canvas>
<img runat="server" Name="theImg" Id="theImg"/>
</asp:UpdatePanel>
...
function screenshotButton() {
canvas.width = videoElement.videoWidth;
canvas.height = videoElement.videoHeight;
canvas.getContext('2d').drawImage(videoElement, 0, 0);
theImg.src = canvas.toDataURL('image/webp');
return true;
};
How can I get a bitmap of theImg in the code behind?
The content of an image doesn't get included in the postback data.
Since you are using an UpdatePanel, you could add a HiddenField into which you also store the Base64 Data URI.
On postback, you can read and parse the content of this hidden field.
<asp:HiddenField ID="HiddenField" ClientIDMode="Static" runat="server" value="" />
Include this in your script.
document.getElementById("HiddenField").value = canvas.toDataURL('image/webp');
Try it by using asp:Image
Then you can set the source programmatically.

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).

How to open a PDF file on click?

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

how to solve postback issue file upload control's path does not exist

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>

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.

Categories

Resources