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).
Related
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?
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.
I am Using asp.net mvc 5. I want to pass array of string from view to controller without using Ajax. Can Anyone help?
This is the controller, value is to be gotten in packagelist[]
public ActionResult Create(Business business, string loc, string serv, string[] packagelist)
{
try
{
if (ModelState.IsValid)
{
var a = locationIds;
business.ServiceId = db.Services.Where(x => x.Title ==serv).Select(x => x.Id).SingleOrDefault();
business.LocationId = db.Locations.Where(x => (x.Title + " (" + x.State + "), " + x.PostalCode)==loc).Select(x => x.Id).SingleOrDefault();
db.Businesses.Add(business);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
foreach(var error in ModelState.Values)
{
foreach(var er in error.Errors)
ModelState.AddModelError("", er.Exception.ToString());
}
}
ViewData["Packages"] = db.BusinessPackages.Select(x => new SelectListItem
{
Text = x.Package,
});
return View(business);
}
catch(Exception ex)
{
ModelState.AddModelError("", ex);
return View(business);
}
}
Have created an hidden input on view
<input type="hidden" name="packagelist" id="packagelist" value="" />
Then set the value of this hidden field via this function
$("#theform").submit(function (e) {
e.preventDefault();
var locdiv=$("#maindiv");
var locations = locdiv.children();
var loc = [];
for (var i = 0; i < locations.length; i++)
{
loc.push(locations.eq(i).text());
}
// SaveLocations(loc);
$("#packagelist").val(loc);
$("#theform").submit();
Now main problem is that when I set value of the input via Jquery and submit it to the controller, controller is considering the array of values as single value.
To receive an array as param in controller, your inputs need specific naming
<input type="hidden" name="packagelist[0]" id="packagelist_0_" value="" />
<input type="hidden" name="packagelist[1]" id="packagelist_1_" value="" />
<input type="hidden" name="packagelist[2]" id="packagelist_2_" value="" />
...
<input type="hidden" name="packagelist[x]" id="packagelist_x_" value="" />
I think you can use cookies.
In JS,
document.cookie = "CookiesName=" + value + "; " + "365;path=/";
In Controller,
var data = Request.Cookies["CookiesName"]
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");
}
I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.
When I click the Upload button, it should show the Image in the Image Box.
When I click the Save button, the path of the uploaded image should be saved in the database.
My issue is the photo gets uploaded, but only after I click the Upload button for the second time.
P.S. I use a Client side function for uploading the photo.
Following are my codes.
CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO
function ajaxPhotoUpload() {
var FileFolder = $('#hdnPhotoFolder').val();
var fileToUpload = getNameFromPath($('#uplPhoto').val());
var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
alert(filename);
if (checkFileExtension(fileToUpload)) {
var flag = true;
var counter = $('#hdnCountPhotos').val();
if (filename != "" && filename != null && FileFolder != "0") {
//Check duplicate file entry
for (var i = 1; i <= counter; i++) {
var hdnPhotoId = "#hdnPhotoId_" + i;
if ($(hdnPhotoId).length > 0) {
var mFileName = "#Image1_" + i;
if ($(mFileName).html() == filename) {
flag = false;
break;
}
}
}
if (flag == true) {
$("#loading").ajaxStart(function () {
$(this).show();
}).ajaxComplete(function () {
$(this).hide();
return false;
});
$.ajaxFileUpload({
url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
secureuri: false,
fileElementId: 'uplPhoto',
dataType: 'json',
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
$('#hdnFullPhotoPath').val(data.upfile);
$('#uplPhoto').val("");
$('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
}
}
},
error: function (data, status, e) {
alert(e);
}
});
}
else {
alert('The photo ' + filename + ' already exists');
return false;
}
}
}
else {
alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
}
return false;
}
PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
<asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
<asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click" OnClientClick="return ajaxPhotoUpload();"/>
</td>
</tr>
</table>
SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Image1.ImageUrl = hdnFullPhotoPath.Value
End Sub
I’d recommend that you drop client side AJAX upload via JS and stick to standard way of uploading. You can probably achieve the same effects without the excessive javascript.
If file type filtering is an issue you can check this post for more details.
Getting extension of the file in FileUpload Control
In either way you have to make a postback so it doesn’t really matter if you upload from JS or the server side except that second method is less complex.
Adding update panel will make this more user friendly and you should be all done.
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="button" id="uploadFile" value="Upload File" />(jpg|jpeg|png|gif)
<div id="uploadStatus" style="color: Red">
</div>
</div>
<script type="text/javascript" language="javascript">
new AjaxUpload('#uploadFile', {
action: 'Handler1.ashx',
name: 'upload',
onComplete: function (file, response) {
if (response == '0') {
$('#uploadStatus').html("File can not be upload.");
}
else {
$('#img').attr("src", "response.path");
}
},
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|jpeg|png|gif)$/i.test(ext))) {
$('#uploadStatus').html("Invalid File Format..");
return false;
}
$('#uploadStatus').html("Uploading...");
}
});
</script>
Then create a handler for uploading image on server
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string a = "1";
if (context.Request.Files != null && context.Request.Files.Count > 0)
{
if (context.Request.Files[0].ContentLength > 1000)
{
a = "0";
}
}
else
{
a = "0";
}
context.Response.Write(a);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.
var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);