Mobile upload using a different image button immediately after selecting image? - css

I would like to use my own .png image to trigger a
<input type="file" id="pictureCapture" accept="image/*; capture=camera" />
and then instantly upload the image to an MVC controller.
So, the first question is how to replace the input tag with a clickable image?
And second, thus far, I've only seen file upload as a 2 part process. You click the browse button, select your file, then click Upload to send the file.
How do I consolidate it so that right after you select the file, it uploads?
Is there a 3rd party control that does all this for me?

Here's what I ended up doing:
Html:
<input type="file" id="pictureCapture" accept="image/*; capture=camera" style="visibility:hidden;" />
<img src="#(Url.Content("~/Images/Mobile/Camera.png"))" />
Javascript:
<script>
$("#uploadPhotoFromCamera").click(function (e) {
e.preventDefault();
$("#pictureCapture").trigger("click");
});
$('#pictureCapture').on("change", function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('pictureCapture');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '#(Url.Action("UploadMobile", "Document"))')
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('success');
}
}
return false;
});
</script>
Controller:
public virtual ActionResult UploadMobile()
{
List<HttpPostedFileBase> files = new List<HttpPostedFileBase>();
for (int i = 0; i < Request.Files.Count; i++)
{
files.Add(Request.Files[i]); //Uploaded file
}
// Do whatever now with your list of files
return Json("Uploaded " + Request.Files.Count + " files");
}

Related

View not returned properly in ASP.NET MVC Core 6

On click of the button, a javascript function is called that captures the snapshot from the camera and sends it to process. On backed, we get the image and do some process and get the data in an object called "doc". Upto here the system works fine, but the data that I got in "doc" object doesn't seem to be printed on the page.
Here's the button
<input type="button" value="Capture Snapshot" onClick="CaptureSnapshot()">
And here's the javascript
<script language="JavaScript">
function CaptureSnapshot() {
Webcam.snap(function (data) {
// display results in page
document.getElementById('results').innerHTML = '<img src="' + data + '"/>';
// Send image data to the controller to store locally or in database
Webcam.upload(data,
'/Home/UploadFile',
function (code, text) {
Webcam.reset();
//alert('Snapshot/Image captured successfully...');
});
});
}
</script>
And this is the C# method written in the controller
public async Task<IActionResult> UploadFile()
{
var files = HttpContext.Request.Form.Files;
if (files != null && files.Count > 0)
{
foreach (var uploadedFile in files)
{
if (uploadedFile.Length > 0)
{
var fileName = uploadedFile.FileName;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", fileName);
HttpContext.Session.SetString("UploadedFile", fileName);
byte[] imageBytes = ConvertToBytes(uploadedFile);
Document doc = ProcessDocumentImage(imageBytes);
ViewData["Document"] = doc;
}
}
}
else
return Content("file not selected");
return View("Index", "Home");
}
If I put a breakpoint on "doc", I get the data but it doesn't go on the page. What I found is that the page is not submitted at all, maybe this is the reason.
Any ideas to solve this?

Upload files, show filenames on form immediately, BUT files get only uploaded to server om Form submit

I'm new to mvc and have a little trouble figuring out how to upload files to the server .
I have a form where the user enters name , address, city , upload files.
The user must be able to upload max 3 files . After the user has selected eg . 2 files , we display immediately files names on the form like this:
Uploaded files:
gif.dk
hitme.gif
BUT the selected files should ONLY be uploaded to the server after the form is submitted to server.
You can display a list of files to be uploaded by subscribing to the change event of the upload control in jQuery.
Controller:
public class UploaderController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Multiple(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
}
}
return View("Index");
}
}
View:
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#uploadFiles').on("change", function () {
var fileUpload = $(this);
var files = fileUpload.context.files;
$("#files").empty();
$("#files").append("<h3>List of files to be uploaded:</h3>");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var name = file.name;
var div = "<div>File name:" + name + "</div>";
$("#files").append(div);
}
});
});
</script>
</head>
<body>
#using (Html.BeginForm("Multiple", "Uploader", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="multiple">
<input id="uploadFiles" type="file" class="multiple" name="files" multiple />
</div>
<button class="btn btn-default">Upload</button>
<div id="files">
</div>
}
</body>
Output:
It is just indication of files which you have selected for upload.
But files will be upload to server only after you submit form.

how to return a value from JsonResult to the bootstrap fileinput

Good evening, I'm using the api bootstrap fileinput and I wonder if you can return a value with ContetResult and uses it in my View.
my Test Controller method ContentResult (just a test):
public ContentResult upload()
{
string name = "";
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
name = file.FileName;
}
return Content("{\"name\":\"" + name + "\"}", "application/json");
}
and my View:
<input id="input-701" name="kartik-input-701[]" type="file" multiple=true class="file-loading" />
<input type="text" class="file_name" />
<script type="text/javascript">
$("#input-upload").fileinput({ 'showUpload': true, 'previewFileType': 'any' });
$("#input-701").fileinput({
uploadUrl: '#Url.Action("upload", "Home")', // server upload action
uploadAsync: false,
maxFileCount: 50,
sucess: function (e, data) {
$('.file_name').html(data.result.name);
}
});
</script>
so I want to do something like this illustrative atributte: sucess
Thanks for the help!
Just Insert value in textbox
$('.file_name').val(data.result.name);

jQuery and #Html.TextBoxfor()

I currently have the following code:
[HttpPost]
public ActionResult Index(IList<LocalPageModel> postPages,
IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0))
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"),
fileName);
file.SaveAs(path);
}
}
}
else
{
ManagePagesModel mod = new ManagePagesModel
{
PostPages = postPages
};
return View("Index", mod);
}
return RedirectToAction("Index");
}
In my view, I have a JavaScript button which will add a div so that the user can post another page such as:
$("#add-page").click(function () {
$("#page").append('<div id="page"> #Html.TextBoxFor(u => u.PostPages[0].Title) </div>');
});
How do I make it so that when the user clicks on the JavaScript button, the new text will be appended to the page and u.PostPages[x] will be incremented?
If you want to do it all on the client (no AJAX), maybe don't use the MVC helpers at all, and do it manually instead - you know the HTML that will be rendered, so just do that:
var i = 0;
$("#add-page").click(function () {
$("#page").append('<input type="text" name="PostPages[' + (i++) + '].Title">');
});
Maybe clean the code up a bit so the quotes don't get too confusing, but you get the idea...
You didn't past your view, but I assume you have the following at the top:
#model = ManagePagesModel
If that's the case, you can then use the following #foreach to loop through the page models:
$("#add-page).click(function() {
#foreach(var pageModel in Model.PostPages){
$("#page").append('<div id="page"> #Html.TextBoxFor(u => pageModel.Title) </div>');
});
To increment u.PostPages[x] you may use following code:
<script>
var i = 0;
$("#add-page").click(function () {
i++
$("#page").append('<div id="page"> #Html.TextBoxFor(u => u.PostPages['+i+'].Title') </div>');
});
</script>
Here is small working example: jsfiddle

Image Upload with preview

preview an image just after browsing and before uploading in IE 7.0 using asp.net and vb.net or java script.i have tried below coding
function DoPreview()
{
var filename = document.form1.filesent.value;
var Img = new Image();
// if (navigator.appName == "Netscape")
// {
// alert("Previews do not work in Netscape.");
// }
// else
//{
Img.src = filename;
document.images[0].src = Img.src;
// }
}
function CheckUpload()
{
var filename = document.form1.filesent.value;
var extension;
var valid = true
var Img1 = new Image()
if (navigator.appName == "Netscape")
{
alert("This upload function cannot be used with Netscape.");
valid = true;
}
else if (filename == '')
{
valid = false;
alert("Please include a file.");
}
else
{
extension = filename.substring(filename.length - 3, filename.length);
if (extension.toUpperCase() != 'jpg')
{
valid = false ;
alert("The file must be a jpg.");
}
else
{
Img1.src = filename;
if ((Img1.height == 0) || (Img1.width == 0))
{
valid = false;
alert("The file is invalid.");
}
else
{
document.form1.height.value = Img1.height;
document.form1.width.value = Img1.width;
}
}
}
return valid
}
<form method="post" action ="Default.aspx" enctype="multipart/form-data" name="form1" onsubmit="return CheckUpload()">
<input type="hidden" name="height" value="0" />
<input type="hidden" name="width" value="0" />
<input type="file" name="filesent" onchange ="DoPreview()" />
<br/>
</form>
<img id ="imagepreview" src="" name="image1" alt ="Image" />
its working in IIS 5.1 but image preview not displaying in IE 7.0
You cant get preview for the image which you selected in File Upload control. Actually image can view only through virtual directory of server in browser using URL. The above code shows that you are trying to set preview of an image which is client side (not stored in server) and this is not possible. You can do image preview by storing the image in server side (uploading the image to server).

Resources