I want to get image preview before uploading any image in my asp.net webform. I am doing this by the following code. But after clicking Save button I want to upload the image to the server. In my codebehind I am getting src="" for <img>. What can I do to get the binarydata back to save my file.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var link = $(fileInput).siblings('.thumb').attr('src');
alert(link);
var img = document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br />
<img id="thumbnil" class="thumb" style="width: 20%; margin-top: 10px;" src="" alt="image" runat="server"/>
<asp:Button runat="server" Text="Save" OnClick="Unnamed_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks in advance..
### Undated whole Answer ###
Option 1:
dont read the img-tag src-attribute, the client cant update it on server side and it wont be "post-back". use an input field like this
<form...>
...
<input class="image-data" type="hidden" id="imageString" runat="server" />
...
</form>
and in the Js-Code add this dataurl as value of this field.
...
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
//... add this, it's searches for the input-field, to be able to post the String to the Server
$(".image-data").val(e.target.result);
};
...
Update:
On the Server you can read the Data like this.
string imageData = imageString.Value;
Option 2:
you could also do this:
alter your asp.net-file
<!-- add enctype=... -->
<form id="form1" runat="server" enctype="multipart/form-data">
...
<!-- add name=... -->
<input type="file" accept="image/*" onchange="showMyImage(this)" name="uploadImage" />
...
in the Codebehind:
HttpPostedFile imageFile= Request.Files["uploadImage"];
if (imageFile && imageFile.ContentLength > 0)
{
// ... Use the imageFile variable as you please
}
Which Option depends, what you want to do with the data.
Related
Is there any way to select all text within a multiline asp:textbox and copy it to client clipboard by clicking a button, using c#?
Thank you in advance.
You can use document.execCommand("copy"); just be aware that this is supported by new browsers mostly and as far as I know there is no support for Safari:
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCopy").click(function () {
var id = "#" + "<%= txtText.ClientID %>";
try {
$(id).select();
document.execCommand("copy");
}
catch (e) {
alert('Copy operation failed');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtText" runat="server" Text="Some sample text to copy"></asp:TextBox>
<button id="btnCopy">Copy</button>
</form>
</body>
Tested and works with the following browsers:
IE 11 and up
Google Chrome 51.0.2704.84
Firefox 43.0.1
I think #Denis Wessels answer was great but used plain textarea instead of asp:TextBox, therefore I want to write my own that includes asp:TextBox control.
Consider you have a multi-line text area with asp:TextBox server control and a button to copy content into clipboard:
<asp:TextBox ID="TextArea" runat="server" TextMode="MultiLine">
<button id="copy">Copy to Clipboard</button>
Use jQuery and a JS function similar to this:
<script type="text/javascript">
$(document).ready(function () {
$("#copy").click(function() {
// use ASP .NET ClientID if you don't sure
// for ASP .NET 4.0 and above, set your ClientID with static mode
var textarea = "<%= TextArea.ClientID %>";
$(textarea).select();
$(textarea).focus(); // set focus to this element first
copyToClipboard(document.getElementById(textarea));
});
});
function copyToClipboard(elem)
{
var result;
var target = elem;
startPoint = elem.selectionStart;
endPoint = elem.selectionEnd;
var currentFocus = document.activeElement;
target.setSelectionRange(0, target.value.length);
try
{
// this may won't work on Safari
result = document.execCommand("copy");
}
catch (e)
{
return alert("Copy to clipboard failed: " + e);
}
// returning original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
elem.setSelectionRange(startPoint, endPoint);
return result;
}
</script>
Reference with minor changes: https://stackoverflow.com/a/22581382, https://stackoverflow.com/a/30905277
Note that for ASP .NET 4 and above you can set static ClientID:
<asp:TextBox ID="TextArea" runat="server" TextMode="MultiLine" ClientID="TextArea" ClientIDMode="Static">
thus you can use $("#TextArea") directly rather than $("<%= TextArea.ClientID %>").
You can use this class:
System.Windows.Forms.Clipboard.SetText(..) <= Sets the text to clipboard,
Inside SetText(), you put textbox.Text to get the text from the multiline asp.net textbox.
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<center>
<p id="p1">Hello, I'm TEXT 1</p>
<p id="p2">Hi, I'm the 2nd TEXT</p><br/>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<br/><br/><input type="text" id="" placeholder="TEST it here;)" />
</center>
Just got my hand on a script that I wish to use to upload files in my application. I can't really use any of the existing controls as I need to do some specific alterations to paths and stuff before the files are uploaded.
I have the following (incomplete) code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="../plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="../plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<form enctype="multipart/form-data">
<span class="btn btn-file btn-primary" id="media-upload-btn">
<span class="fileupload-new" title="Accepted formats (.gif, .jpeg, .png)">Choose image(s)</span>
<span class="fileupload-exists">Choose another image</span>
<input id="user-file-to-upload" type="file" name="file" accept="image/gif, image/jpeg, image/png"/>
</span><br /><br />
<input type="button" onclick="upload();" value="Upload" />
</form>
</div>
</form>
<script type="text/javascript">
function upload() {
alert("test");
// var acceptedFileSize = $('#upload-image-size').val();
var acceptedFileSize = 10000;
alert(acceptedFileSize);
if (window.FormData !== undefined) {
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
var fileSize = files[i].size;
sp.base.log('fileSize(b): ' + fileSize);
sp.base.log('acceptedFileSize(kb): ' + acceptedFileSize);
if (parseInt(fileSize) > (parseInt(acceptedFileSize) * 1024)) {
$('#btnUpload').button('reset');
sp.base.show('The file is too large!<br>Cant be larger than ' + (parseInt(acceptedFileSize) / 1024) + ' MB. ' + ' and the current file size is ' + Math.round((parseInt(fileSize) / 1024 / 1024)) + ' MB.', 'error', 12000);
return false;
}
}
var url = "upload2.aspx";
sp.base.call(
'POST',
url,
data,
function (returnData) {
alert("Works");
onSuccessUploadImage(returnData, callback);
},
null,
function () {
// onError
alert("Error");
$('#btnUpload').button('reset');
},
null,
true,
false
);
}
}
</script>
Right now, I'm unsure of how to actually collect the files into the files object, and I would also like to be able to add multiple files, not just one.
When a user wants to upload a file (currently there are 4 places in the form that allow for this), they first have to “Choose File” and then they have to click on “Upload”. If they miss the 2nd "Upload" step, there is no indication to them or us.
Is there a way to combine the “two-step” process to a single step (select and upload).
Use this link to know more about it
http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/
And you can also use this code
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= fileupload1.ClientID %>').on('change', function (e) {
console.log('change triggered');
$('#<%= btn.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
});
});
</script>
</form>
</body>
Code behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
I'm trying to realize little program in ASP, which count numbers with timer. I use this task with JavaScript and have some problems when I call it from sharp code. So, this code works good:
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function counter() {
var q = Number(document.getElementById("TextBox1").value);
var i = Number(document.getElementById("Text1").value);
if (i < q) {
i += 1;
document.getElementById("Text1").value = i;
setTimeout("counter()", 10);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True"></asp:TextBox>
<input id="Button1" type="button" value="button" onclick="counter()" />
<input id="Text1" name="Text1" type="text" value="0"/>
</div>
</form>
</body>
Random function generates value in Page_Load and put in TextBox1. In this code I used inputs for everything. But I want to use asp controls and then I tried to rewrite the same with and call script from sharp, but my code doesn't work:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Text1" runat="server" Text="0"></asp:Label>
</div>
</form>
</body>
and sharp code:
string str = "function counter() {
var q = Number(document.getElementById(\"TextBox1\").value);
var i = Number(document.getElementById(\"Text1\").value);
if (i < q) { i += 1; document.getElementById(\"Text1\").value = i;
setTimeout(\"counter()\", 10) } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "counter", str, true);
Button1.Attributes.Add("onclick", "counter()");
and this what I see in html output:
<script type="text/javascript">
//<![CDATA[
function counter() { var q = Number(document.getElementById("TextBox1").value); var i = Number(document.getElementById("Text1").value); if (i < q) { i += 1; document.getElementById("Text1").value = i; setTimeout("counter()", 10) } }//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAPaDIYgDxN4mARW8/nWYR/uESCFkFW/RuhzY1oLb/NUVM34O/GfAV4V4n0wgFZHr3e02FqXa4CDb/Y32Jm7yDyEftd8wArFmKGvvW1nftcl6Q==" />
</div>
<div>
<input name="TextBox1" type="text" value="1332073012" id="TextBox1" />
<input type="submit" name="Button1" value="Button" onclick="counter();" id="Button1" />
<span id="Text1">0</span>
</div>
</form>
</body>
I see script and button with onclick="counter()" method, but it doesn't work, and I don't know why. and I couldn't find the similar samples.
the problem has little to do with running the code on the server, and more to do with the change of the node Text1 from input to span.
first, change all references to Text1 to get the property innerHTML instead of value, second, add a return false to the click event so the form doesn't get submitted. Finally, you're missing a ; in the C# code block, and should invoke setTimer with a function, not a string.
the resulting code would look like this:
string str = "function counter() {
var q = Number(document.getElementById(\"TextBox1\").value);
var i = Number(document.getElementById(\"Text1\").innerHTML);
if (i < q) { i += 1; document.getElementById(\"Text1\").innerHTML = i;
setTimeout(function(){counter();}, 10); } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "counter", str, true);
Button1.Attributes.Add("onclick", "counter(); return false;");
BTW, if you can script it on the client side, you should. Writing javascript on the server side definitely violates the unobtrusive principle
I'm new here.
I'm trying to make an application that calculates distance and driving time between two adresses using google maps API.
My problem is that google DirectionsService() doesn't seem to respond. and I can't figure it out. I have been trying to figure it out for one week now.
I hope you guys can help.
the problems seems to be in gmapApi.js
here is my code.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function postbackObj() {
var orig = document.getElementById('<%= txbOrigin.ClientID %>').value;
var dist = document.getElementById('<%= txbDestination.ClientID %>').value;
var temp = showLocation(orig, dist);
__doPostBack('gmAPIObj',temp);
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript">< /script>
<script type="text/javascript" src="gmapApi.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txbOrigin" Text="" runat="server" />
<asp:TextBox ID="txbDestination" Text="" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Search" OnClientClick="postbackObj()"/>
<p>
< asp:Label runat="server" ID="lblPrint" />
</p>
</div>
</form>
</body>
</html>
gmapApi.js
function showLocation(orig, dist) {
var directionService = new google.maps.DirectionsService();
var t = "";
var request = {
origin: orig,
destination: dist,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionService.route(request, function (response, status) {
if (status != google.maps.DirectionsStatus.OK) {
alert(status + " \nreq. failed.");
}
else {
t = request.origin + ';' + request.destination + ';' + response.routes[0].legs[0].distance.value + ';' + response.routes[0].legs[0].duration.value;
}
});
return t;
}
the response variable is null and the status variable is emptystring in the directionService.route(request, function (response, status)
I have tried to change to without lock. And I have tried to place the tags in the body tag without lock.
the rendered html code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
<script type="text/javascript">
function postbackObj() {
var orig = document.getElementById('txbOrigin').value;
var dist = document.getElementById('txbDestination').value;
var temp = showLocation(orig, dist);
__doPostBack('gmAPIObj',temp);
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="gmapApi.js"></script>
</head>
<body>
<form method="post" action="Default.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MjMyMzMwNTZkZHxi8IJlhy7bL8nAZqZfL2Vh4Yr8uF80ja6jX9Ypc87B" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBALsorucDwLTmobsAwK0weWLAwLCi9reA32PxME86E6mQhRTgBkF7cdktbiURIpf/IzKvAs5PHwI" />
</div>
<div>
<input name="txbOrigin" type="text" value="tilst" id="txbOrigin" />
<input name="txbDestination" type="text" value="aarhus" id="txbDestination" />
<input type="submit" name="btnSubmit" value="Search" onclick="postbackObj();" id="btnSubmit" />
<p>
<span id="lblPrint"></span>
</p>
</div>
</form>
</body>
</html>
thanks in advance.
requesting the directionService is an asynchronous process, your variable t inside the function showLocation will not be modified by the call of directionService.route()
call __doPostBack('gmAPIObj',t) from within the successfull callback of directionService.route() instead.
function postbackObj() {
var orig = document.getElementById('txbOrigin').value;
var dist = document.getElementById('txbDestination').value;
showLocation(orig, dist);
}
//-----
function showLocation(orig, dist) {
var directionService = new google.maps.DirectionsService();
var t = "";
var request = {
origin: orig,
destination: dist,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionService.route(request, function (response, status) {
if (status != google.maps.DirectionsStatus.OK) {
alert(status + " \nreq. failed.");
}
else {
t = request.origin + ';' + request.destination + ';' + response.routes[0].legs[0].distance.value + ';' + response.routes[0].legs[0].duration.value;
__doPostBack('gmAPIObj',t);
}
});
}