Adding Images to div from codebehind in Asp.Net - asp.net

I am uploading some images using plupload and adding those images to div container.And after performing some options I need to upload the edited Images again to the same div from codebehind.
Is that possible to do so?If so how can I modify my code:
This is how I'm trying to upload Images and adding them to div(thumbs):
<script type="text/javascript">
$(function () {
$("#<%=uploader.ClientId%>").plupload({
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: 'Editor.aspx',
max_file_size: '10mb',
max_file_count: 21,
chunk_size: '1mb',
unique_names: true,
rename: true,
dragdrop:true,
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
],
flash_swf_url: 'js/plupload.flash.swf',
silverlight_xap_url: 'js/plupload.silverlight.xap'
});
$('form').submit(function (e) {
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
if (uploader.files.length > 0) {
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
}
else
//alert('You must at least upload one file.');
return false;
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FilesAdded', function (up, files) {
var i = up.files.length,
maxCountError = false;
plupload.each(files, function (file) {
setTimeout(function () {
up.start();
}, 100);
if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) {
$.msgBox({
title: "Info",
content: "Uuh! Please don't put me any more files.<br>Maximum Upload limit is only 20 Images.<br>Rest of the Images will be removed.",
type: "info",
showButtons: true,
opacity: 0.1,
autoClose: false
});
uploader.removeFile(up.files[i - 1]);
} else {
}
});
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FileUploaded', function (up, file, res) {
$('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
showStickySuccessToast();
}
});
});
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (!length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
</script>
After editing operation which I am doing it in my codebehind I have saved all those Images to one folder where users can save them.So Now What I want to do Is add all those existed Images on my server folder to be displayed it in the same div(thumbs)where I am adding Images using the uploader at the beginning.

To access a control in code behind, the control must have runat="server". However, it is simpler to use a Panel control instead of a div. A Panel control renders as a div so any client JavaScript will continue to work.
Image NewImage = new Image();
NewImage.ImageUrl= MapPath(#"~\Images\april.jpg");
Panel1.Controls.Add(NewImage);

Related

flip or change camera during call webrtc

i have mobile app which is developed in xamarin form. I am running webview on that for video call, now everything is working fine only i am not able to switch front or back camera during running video call.
Here is what i have tried so far but didnt succeed.
i have added select option in html code where i can choose front or back camera and here is the code of javascript
$('select').on('change', function (e) {
navigator.mediaDevices.enumerateDevices().then(function (devices) {
var valueSelected = $("#myselect option:selected").val();
alert(valueSelected);
//var myselect = 0;
if (valueSelected == "0") {
var cameras = [];
devices.forEach(function (device) {
'videoinput' === device.kind && cameras.push(device.deviceId);
});
var constraints = { video: { deviceId: { exact: cameras[0] } } };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { // Set your video displays
window.localStream = stream;
myapp.setMyVideo(window.localStream)
if (callback)
callback();
}, function (err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
else {
var cameras = [];
devices.forEach(function (device) {
'videoinput' === device.kind && cameras.push(device.deviceId);
});
var constraints = { video: { deviceId: { exact: cameras[1] } } };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { // Set your video displays
window.localStream = stream;
myapp.setMyVideo(window.localStream)
if (callback)
callback();
}, function (err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
//var myselect = $("#myselect option:selected").val();
});
});
when video call start by defaul it open back camera

How to send image into a specific folder?

I have an input element that selects an image as follows:
HTML Code
<input type="file" id="uploadEditorImage" />
Javascript Code
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
And Code in MVC controller
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.
Thank you.
in your html:
<input type="file" id="FileUpload1" />
script:
$(document).ready(function () {
$('#FileUpload1').change(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
console.log(files);
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
and backend:
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Content/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

return JSON from MVC equivalent to web forms

I'm trying to upload files using plupload and in MVC I have code like this:
public ActionResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
and now I want to do same in web forms. I have added these code in my submit button click
protected void submitBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
}
and I need to send the success=true to my plupload javascript code to write these photos in my folder.
$(document).ready(function () {
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles',
container: document.getElementById('container'),
url: '/Admin.aspx',
flash_swf_url: '/Scripts/Moxie.swf',
silverlight_xap_url: '/Scripts/Moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
]
},
init: {
PostInit: function () {
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
UploadProgress: function (up, file) {
_file_name = file.name;
$('#PhotoBox').val(_file_name);
console.log(file.name);
},
Error: function (up, err) {
alert("\nError #" + err.code + ": " + err.message);
}
}
});
uploader.init();
});
so Is there any equivalent of
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
for asp.net Web Forms?
simply put
if (!IsPostBack) {
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
}
in your page load event and everything will okay

Best way to load css for partial views loaded using ajax

I'm working on my application that creates tabs dynamically and fills them with partial views using ajax.
My question is: how to load css for this views? What's the best way to do it? I mean I can't load the css file on the partial view (no head) or could i?
Some code: the tabManager (a partial view loaded on the main page):
<script>
var tabTemplate = "<li class='#{color}'><a id='#{id}'href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"; // base format for the tabs
$(document).ready(function () {
var tabs = $("#tabs").tabs(); // apply jQuery ui to tabs
$("a.menuButton").click(function () {
var urlContent = $(this).data("direction");
var label = $(this).data("label");
var idTab = $(this).data("id");
var color = $(this).data("color");
var exist = false;
var counter = 0;
$('#tabs ul li a').each(function (i) { // tab already exist o no hay que crear una tabla?
counter = counter + 1; // index counter
if (this.id == "#" + idTab) { // Tab already exist?
exist = true;
$("#tabs").tabs("option", "active", counter - 1); //activate existing element
}
});
if (idTab == "-1") { // is a clickable element?
exist = true;
}
if (exist == false) { // create new tab
addTab(idTab, label, color); // basic tab
getTabContent(idTab, urlContent); // content for new tab
var lastTab = $('#tabs >ul >li').size() - 1; // get count of tabs
$("#tabs").tabs("option", "active", lastTab); // select last created tab
}
});
function getTabContent(idT, urlC) { // ajax call to partial view
$.ajax({
url: urlC,
type: 'GET',
async: false,
success: function (result) {
$("#"+idT).html(result);
}
});
};
function addTab(idT, labT, color) { //create new tab
var label = labT,
id = idT,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{id\}/g, "#" + id).replace(/#\{color\}/g, color)),
tabContentHtml = "Cargando...";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
}
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});
</script>
<div id=tabs>
<ul>
</ul>
A button example:
<li><a class="menuButton" href="#" title="Permisos" data-id="tab3" data-direction="Permiso/_Administrar" data-label="Label" data-color="blue"><img src="#Res_icons.More">Permisos</a><li>
i found my answer here: http://dean.resplace.net/blog/2012/09/jquery-load-css-with-ajax-all-browsers/
the code:
<script type="text/javascript">
$(document).ready(function () {
$("head").append("<link href='...' rel='stylesheet'>");
});
</script>

How to load images on page refresh from folder using Asp.Net

I would like to know that On Page refresh I would like to display more than 40+ images which are already existed in my server folder to be displayed in a div control which already exists and add those images to that div
As of now I can display one image using as shown below:
Preview.ImageUrl = "~/DownloadImages/" & Session("tempDir").ToString & "/" & filename
I would like to know the better solutions!
Here is how the images are generated:
<script type="text/javascript">
$(function () {
$("#<%=uploader.ClientId%>").plupload({
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: 'Default.aspx',
max_file_size: '10mb',
max_file_count: 21,
chunk_size: '1mb',
unique_names: true,
rename: true,
dragdrop: true,
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
],
flash_swf_url: 'js/plupload.flash.swf',
silverlight_xap_url: 'js/plupload.silverlight.xap'
});
$('form').submit(function (e) {
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
if (uploader.files.length > 0) {
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
}
else
//alert('You must at least upload one file.');
return false;
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FilesAdded', function (up, files) {
var i = up.files.length,
maxCountError = false;
plupload.each(files, function (file) {
setTimeout(function () {
up.start();
}, 100);
if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) {
$.msgBox({
title: "Info",
content: "Max Files Reached.",
type: "info",
showButtons: true,
opacity: 0.1,
autoClose: false
});
uploader.removeFile(up.files[i - 1]);
} else {
}
});
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FileUploaded', function (up, file, res) {
$('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
showStickySuccessToast();
}
});
});
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (!length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
</script>
If I know how many Images users can add then it's easy but It's hard to say thats the main issue.
You can use Literal or Image Controls and add them on a Panel (or even a div if you add runat="server" to it on the aspx file)
<div id="existingDiv" runat="server"></div>
I prefer Image controls... something like this: (this is a very simple example of course)
foreach(string imageURL in urlsList)
{
var img = new System.Web.UI.WebControls.Image();
img.ImageUrl=imageURL;
img.Width = 200;
img.Height = 100;
this.div1.Controls.Add(img);
}
EDIT:
Inside urlsList i load the urls like so: (VB)
Dim urls As New List(Of String) 'I dont know if you need another parenthesis here on VB...
urls.Add("imageurl1")
urls.Add("imageurl2")

Resources