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.
Related
I am building an MVC based ASP.NET application. One of the functionalities should be to be able to upload files asynchronously using a progress bar.
I've had success with uploading files without the progress bar. The code below does that.
View Code:
<input class="file" type="file" name="file" id="file" />
<input type="submit" name="submit" value="Upload" />
Controller Code:
public ActionResult Upload(){
return View();
}
[HttpPost]
public ActionResult Upload(Resource resource)
{
try
{
if (resource.File.ContentLength > 0)
{
var fileName = Path.GetFileName(resource.File.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Resources"), fileName);
resource.File.SaveAs(path);
}
}
catch (Exception e)
{
Console.WriteLine("Cannot upload file. Exception of type : {0}", e.ToString());
}
return RedirectToAction("Upload");
}
This code works absolutely fine. With slight modifications, I am even able to upload multiple files. But, even though I've tried finding it, I am not able to upload files using a progress bar.
Any help is appreciated.
This is how I do it - the controller code is much the same, but the client has some javascript in it to monitor and update progress of the ajax posting. The UI Html is like this:
<div id="uploadDetails" class="form-group">
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" name="file" id="file" />
</span>
</span>
<input type="text" id="filename" class="form-control fullwidth" readonly />
<span class="input-group-btn">
<button class="btn btn-primary" type="button" id="uploadFile"><span class="glyphicon glyphicon-upload"></span> Upload File </button>
</span>
</div>
</div>
And the javascript for the upload like this:
$(document).on('click', '#uploadFile', function (e) {
var fileElement = document.getElementById('file');
var file = fileElement.files[0];
var formData = new FormData();
formData.append("filename", fileElement.files[0].name);
formData.append("id", '#Model.SharedIP.Id');
formData.append("file", file, fileElement.files[0].name);
var html = $('#uploadFile').html();
$('#uploadFile').html('Uploading...');
$.ajax({
url: "#Url.Action("UploadFile", "SharedIP")",
type: "POST",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
$('#uploadFile').html('Uploading... ' + Math.round((evt.loaded / evt.total) * 100) + '%');
}
else $('#uploadFile').html('hmmm');
}, false);
return xhr;
},
success: function (results) {
updateFilesList();
$('#uploadFile').html(html);
fileElement.files = [];
var control = $('#file');
control.replaceWith(control.clone(false));
$('#filename').val("")
},
error: function (xhr, ajaxOptions, thrownError) {
$('#uploadFile').html(html);
alert(xhr.responseText);
}
});
});
For completeness, here's the Controller signature, it's .net Core RC1 so might not work in your target framework, but you will get the idea.
[HttpPost]
public IActionResult UploadFile(string filename, Guid id, IFormFile file)
{
IPFile ipfile = new IPFile()
{
ContentType = file.ContentType,
DateUploaded = DateTime.Now,
Filename = filename,
SharedIPId = (id == Guid.Empty ? (Guid?)null : id),
Id = Guid.NewGuid(),
UploadedBy = User.Alias(),
};
ipfile = FileManager.AddFileFromStream(User.Alias(), ipfile, file.OpenReadStream());
return Ok(ipfile);
}
Hope that answers your question.
[EDIT] Just realised this isn't a "progress bar" - but it's got all the workings and % display - to put a progress bar in, you'd just apply CSS to an element that renders the % graphically for you - see posts like http://www.w3schools.com/bootstrap/bootstrap_progressbars.asp for examples.
Here is the code that I have tried. It's a bare minimum code but works as expected. It still has some bugs and I would appreciate if someone could make it bug free.
Some bugs:
Progress bar does not reset on a new file upload.
Add a button to do the upload (I can do it myself as well).
Model Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NewDeploymentsTesting.Models
{
public class UploadFilesResult
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
}
Controller Code:
using NewDeploymentsTesting.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NewDeploymentsTesting.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadFilesResult>();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0) continue;
string savedFileName = Path.Combine(Server.MapPath("~/Content/Resource"), Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
r.Add(new UploadFilesResult()
{
Name = hpf.FileName,
Length = hpf.ContentLength,
Type = hpf.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
}
}
View Code:
#{Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Uploading Files</title>
<link href="~/Content/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap/bootstrap-theme.css" rel="stylesheet" />
<link href="~/Content/jquery.fileupload.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.ui.widget.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.fileupload.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Home/UploadFiles',
autoUpload: true,
done: function (e, data) {
$('.file_name').html(data.result.name);
$('.file_type').html(data.result.type);
$('.file_size').html(data.result.size);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
</script>
</head>
<body>
<div class="container">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add Files ...</span>
<input id="fileupload" type="file" name="files[]" multiple />
</span><br />
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only">0% Complete</span>
</div>
</div><br />
<div class="file_name"></div><br />
<div class="file_type"></div><br />
<div class="file_size"></div><br />
</div>
</body>
</html>
Here is what it looks like on the browser window.
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.
This question already has answers here:
generate random string for div id
(17 answers)
Closed 8 years ago.
How to set random id for dynamic created textbox and div.i have to set different id for dynamic created div and textbox.please give id for randomly
my code is here
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" />' +
'<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
</script>
</head>
<body>
<form id="Form2" runat="server">
<input id="btnAdd" type="button" value="Add Text" onclick="AddTextBox()" />
<br />
<br />
<div id="TextBoxContainer">
</div>
</form>
<script type="text/javascript">
var randomId = 0;
function GetDynamicTextBox(value) {
var newRandomIdOfTextBox = "dynamicTextBox" + randomId++ + "";
return '<input name = "DynamicTextBox" type="text" id="' + newRandomIdOfTextBox +'" />' +
'<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
</script>
randomId starts from 0 and every time you add a new text box it will increment by one making it unique..
you can set id ="'sometext'+Math.random();"
Please let me know if this helps
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);
}
});
}