Tag Archives: FileUpload

FileUpload

[RESOLVED]Reading CSV file for validation and after that saving it on server in MVC 4

Hi,

I have CSV file upload functionality in MVC4. Below my code is working fine on local machine, when I deploy same code on server I am getting error "Could not find file at C:WindowsSystem32InetSrv".

  [HttpPost]
        public ActionResult Upload(HttpPostedFileBase UploadedFile)
        {
            try
            {
                var fp = Path.GetFileName(UploadedFile.FileName);
                var reader = new StreamReader(UploadedFile.FileName);
                while (!reader.EndOfStream)
                {

                        string[] str = reader.ReadLine().Split(‘,’);  //Validation Logic.

                 }

                reader.Close();
                reader.Dispose();
                UploadedFile.SaveAs(@"d:FileUploadDemo" + fp);
                return View("Index");
            }
            catch (Exception)
            {
                return View("Index");
            }
        }

But If I comment below file reading code,

  var fp = Path.GetFileName(UploadedFile.FileName);
                var reader = new StreamReader(UploadedFile.FileName);
                while (!reader.EndOfStream)
                {
                    string[] str = reader.ReadLine().Split(‘,’);
                }
                reader.Close();
                reader.Dispose();

then my file is getting saved on the server perfectly fine.

But, Before saving a file, I want to validate the file data. I have implemented client side code but it is not working in IE browsers. So wanted to do server side validation.

Or any client side code, working in IE8+ browsers (without asking user to activate ActiveX object) is greatly appreciated.

The filename only contains the name of the file itself, it is for "information" purposes, the file isn’t actually saved to disc until you save it using SaveAs, so you can’t access it yet via StreamReader.  If you want to read its contents you need to access
the file data via the InputStream and convert it to a string that you can then validate

http://stackoverflow.com/questions/16030034/asp-net-mvc-read-file-from-httppostedfilebase-without-save

[RESOLVED]Mock Response.Cookies.Add(…) in MVC unit testing

The basic problem is that the controller I’m testing calls Response.Cookies.Add(…) but since the unit test is not in an HTTPContext, Response is null and I get an exception. Can someone give me an example. ?

Look at hanselmann 

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

how it mocks Request and Request.Files

Same way you will mock Request and Request.Cookies

You have to abstract access to non-testable resources like cookies.  Create an interface and a class that implements your interface

namespace TestMvc.Managers
{
    public interface IClientStorageManager
    {
        void Store(string key, string value);
    }
}

namespace TestMvc.Managers
{
    public class CookieStorageManager : IClientStorageManager
    {
        public void Store(string key, string value)
        {
            HttpCookie c = new HttpCookie(key);
            c.Value = value;

            System.Web.HttpContext.Current.Response.Cookies.Add(c);
        }
    }
}

Use this rather than accessing cookies direct

public class HomeController : Controller
{
    private IClientStorageManager clientStorageManager;

    public HomeController()
        : this(new CookieStorageManager())
    {
        // you can use DI to do this instead
    }

    public HomeController(IClientStorageManager clientStorageManager)
    {
        this.clientStorageManager = clientStorageManager;
    }

    public ActionResult Index(string name = null)
    {
        this.clientStorageManager.Store("name", name);

        return View();
    }

You can now mock the storage class from your unit test

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        // I'm using moq, but you can use any mocking framework you want, or even self-shunting
        Mock<IClientStorageManager> storage = new Mock<IClientStorageManager>();

        HomeController c = new HomeController(storage.Object);

        c.Index("Bob");

        storage.Verify(s => s.Store(It.IsAny<string>(), "Bob"), Times.AtLeastOnce());
    }
}

[RESOLVED]Validator for HTML Helper ListBoxFor( )

Hello,

How to validate a html helper listbox using model binding ?

MODEL:

 public class ParentModel
    {        
        public FileUploadModel FileUploadModel { get; set; }
        public ProgramViewModel ProgramViewModel { get; set; }
    } 

public class FileUploadModel
    {        
        [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "jpg", ErrorMessage = "please specify a jpg file only.")]
        [DisplayName("FileName")]
        public HttpPostedFileBase File { get; set; }

        [Required(AllowEmptyStrings=false,ErrorMessage = "Please add an auxiliary state")]
        [MaxLength(100, ErrorMessage = "AuxiliaryState should not be longer than 100 characters.")]
        [DisplayName("AuxiliaryState")]
        public string AuxiliaryState { get; set; }

        public bool IsAllPrograms { get; set; }  
    }
    public class ProgramViewModel
    {        
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }

Controller:

 [HttpPost]
        public ActionResult AuxiliaryProgramMapping(ParentModel model)
        {
            if (ModelState.IsValid)
            {                
                bool isCheckedForAllPrograms =model.FileUploadModel.IsAllPrograms;
                var AuxProgramName = model.FileUploadModel.AuxiliaryState;

                IEnumerable<string> selectedPrograms = model.ProgramViewModel.SelectedPrograms;
                if (selectedPrograms == null)
                {
                       // something
                }
                else
                 {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("You selected – " + string.Join(",", selectedPrograms));
                    string x = sb.ToString();
                 }



                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
                List<AdminDTO> lll = objAdminBussinessLayer.GetActivePrograms();
                foreach (var programs in lll)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = programs.ProgramName,
                        Value = Convert.ToString(programs.ProgramID)
                    };
                    listSelectListItems.Add(selectList);
                }
                ProgramViewModel ProgramsViewModel = new ProgramViewModel()
                {
                    Programs = listSelectListItems
                };

                ParentModel parent = new ParentModel();
                parent.ProgramViewModel = ProgramsViewModel;

                string path = @"D:Temp";

                HttpPostedFileBase photoa = model.FileUploadModel.File;
                if (photoa != null)
                    photoa.SaveAs(path + photoa.FileName);
                return View(parent);

            }
            else
            {
                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
                List<AdminDTO> lll = objAdminBussinessLayer.GetActivePrograms();
                foreach (var programs in lll)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = programs.ProgramName,
                        Value = Convert.ToString(programs.ProgramID)
                    };
                    listSelectListItems.Add(selectList);
                }
                ProgramViewModel ProgramsViewModel = new ProgramViewModel()
                {
                    Programs = listSelectListItems
                };

                ParentModel parent = new ParentModel();
                parent.ProgramViewModel = ProgramsViewModel;
                return View(parent);
            }
        }

VIEW:

@using (Html.BeginForm("AuxiliaryProgramMapping", "AuxiliaryProgramMapping", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
               ... blah blah 

 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
                               
 @* Now how to validate this listbox .. (required)*@
               ... blah blah
             }

 

Hi did you try  this ?

@Html.ValidationMessageFor(model => model.YourModel, "", new { @class = "text-danger" })

i would gladly do that , but the problem is WHERE shall i mention the Required attribute ?

i did like below : but couldnt make it work.

 public class ProgramViewModel
    {
        [Required(ErrorMessage = "Please select atleast one program")]
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }


 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms) 

to make it easy why don’t you just try to use this?

http://jqueryvalidation.org/required-method/ 

M afraid i cant do that , requirement is like this only , i cant do validations from jquery i need to do that using model binding only.

Anyone ???

Hi Ashim,

For this requirement, you need to custom validation.

There are some links that can help you:

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

# Required Attribute on Generic List Property

http://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property

Best Regards

Starain

Starain chen – MSFT

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Thats a good example to override the isvalid method , but the the thing is m new to MVC and i really dont have any idea about how to do custom validation on a listboxfor helper ? Can you please help me out ?

# Required Attribute on Generic List Property

http://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property

This is custom validation on whether the generic list is empty or not , my question is whether the list have any selected item or not ? both are different. 

Hi Ashim,

You could refer to the first link to learn how to custom validation and the second link is the sample about how to check whether the collection is empty or not.

For the form submit, it just sends the selected items data instead of all items. So you just need to check whether the collection has data or not.

Best Regards

Starain

Starain chen – MSFT

So you just need to check whether the collection has data or not.

I tried , but its not working : see this:

MODEL:

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public class IsSelectedAttribute : ValidationAttribute
    {
        public IsSelectedAttribute(string errorMessage) : base(errorMessage)
        {
            this.ErrorMessage = errorMessage;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            try
            {
                if(value == null)
                {
                    validationResult = new ValidationResult(ErrorMessageString);
                }                
            }
            catch (Exception ex)
            {
                // Do stuff, i.e. log the exception
                // Let it go through the upper levels, something bad happened
                throw ex;
            }

            return validationResult;
        }
    }
    public class ParentModel
    {
        public AuxiliaryProgramMappingDTO AuxiliaryProgramMappingDTO { get; set; }
        public FileUploadModel FileUploadModel { get; set; }
        public ProgramViewModel ProgramViewModel { get; set; }
    }    
    public class FileUploadModel
    {        
        [Required(ErrorMessage="Please upload an icon"), Microsoft.Web.Mvc.FileExtensions(Extensions = "jpg", ErrorMessage = "please specify a jpg file only.")]
        [DisplayName("FileName")]
        public HttpPostedFileBase File { get; set; }

        [Required(AllowEmptyStrings=false,ErrorMessage = "Please add an auxiliary state")]
        [MaxLength(100, ErrorMessage = "AuxiliaryState should not be longer than 100 characters.")]
        [DisplayName("AuxiliaryState")]
        public string AuxiliaryState { get; set; }

        public bool IsAllPrograms { get; set; }
    }
    public class ProgramViewModel
    {   
        [IsSelected("Please select atleast one program.")]
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }

VIEW:

 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms) 

After this in Controller when i try to check whether ModelState is valid.Its showing valid ,when it should not.Please recreate the scenario at your end.

Ashim Chatterjee

Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms)

           Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new {  required="required",@class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
                @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms)

add required="required"  attribute to the listbox

cnuonline

add required="required"  attribute to the listbox

You are a life saver … cheers. 

Thanks  a lot. :)

cnuonline

add required="required"  attribute to the listbox

Just One Question : can i add my own error message instead of the default one ?

try this

document.getElementById('ProgramViewModel_SelectedPrograms').setCustomValidity('Please select  a Programs');

where shall i call that .. i tried in document ready , didnt worked .

Is this a main view or a partial view loading after document load?

this is a main view.

Make sure the id of the list box in the statement

Thanks .. :)

[RESOLVED]how can I upload an image and save the url in the database

I want to be able to upload an image to the server but instead of saving the image as byte in the database I want to save the path so that in the view page I call the image by it’s path.also the image when uploaded it should be uploaded in a certain
folder if folder not found create one.all this should be using MVC5 any help is really appreciated

lolo512

I want to be able to upload an image to the server but instead of saving the image as byte in the database I want to save the path so that in the view page

And the problem is …? To save use File.WriteAllBytes. 

I want a full code I don’t know how to do so im a new learner of MVC I appreciate your help

Hi,

For your references:

  1. https://www.youtube.com/watch?v=9LPIu_BvatE
  2. https://www.youtube.com/watch?v=rpmtFvduwyI

Here I do for both save to database or (not and) to a folder, depend on it’s size:

A helper class, is used when save to database:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;

namespace PersonEntity.Model
{
    public static class ConvertFile
    {
        public static byte[] ImageToByte(HttpPostedFileBase imageFile)
        {
            if (imageFile == null) { return null; }
            return (imageFile.ContentType == "image/jpeg" || imageFile.ContentType == "image/gif" || imageFile.ContentType == "image/png") ? FileToByte(imageFile) : null;
        }

        public static byte[] FileToByte(HttpPostedFileBase file)
        {
            byte[] data = new byte[file.ContentLength];
            file.InputStream.Read(data, 0, file.ContentLength);
            return data;
        }
    }
}

Need a partial class to the class where image class is defined, for "File":

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PersonEntity.Model
{
    [MetadataType(typeof(ProductPhotoMetadata))]
    public partial class ProductPhoto
    {
        [DisplayFormat(NullDisplayText = "n/a")]
        //[Required(ErrorMessage = "Please select image file")]
        public HttpPostedFileBase File { get; set; }
    }
}

Controller, add ",File" almost at the end of the "public Action Result:…….,File")] ProductPhoto…….. It si boleded and underlined

        // GET: ProductPhotoes/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
            if (productPhoto == null)
            {
                return HttpNotFound();
            }
            return View(productPhoto);
        }

        // GET: ProductPhotoes/Create
        public ActionResult Create()
        {
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria");
            return View();
        }

        // POST: ProductPhotoes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
        {
            productPhoto.ModifiedDate = DateTime.Now;
            if (productPhoto.File != null)
            {
                if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
                {
                    ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                    return View(productPhoto);
                }
                productPhoto.ImageSize = productPhoto.File.ContentLength;

                /** Photo dibawh 61KB disimpan di database, sisanya disimpan di folder, dengan nama NewGuid() **/
                if (productPhoto.File.ContentLength < 61676)
                {
                    productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
                }
                else
                {
                    productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
                    productPhoto.Photo = null;
                    var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
                    productPhoto.File.SaveAs(path);
                }
            }

            if (ModelState.IsValid)
            {
                db.ProductPhotoes.Add(productPhoto);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

        // GET: ProductPhotoes/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
            if (productPhoto == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

        // POST: ProductPhotoes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
        {
            productPhoto.ModifiedDate = DateTime.Now;

            if (productPhoto.File != null)
            {
                if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
                {
                    ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                    return View(productPhoto);
                }
                productPhoto.ImageSize = productPhoto.File.ContentLength;
                if (productPhoto.File.ContentLength < 61676)
                {
                    productPhoto.PhotoFileName = null;
                    productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
                }
                else
                {
                    productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
                    productPhoto.Photo = null;
                    var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
                    productPhoto.File.SaveAs(path);
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(productPhoto).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

Create.cshtml, attention on "@using (Html.BeginForm(…………………..))"

@model PersonEntity.Model.ProductPhoto

@{
    ViewBag.Title = "Create: " + @EstateAgency.Admin.Resource.Product + " Photo";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("Create", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ProductPhoto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.File, new { type = "file" })
                @Html.ValidationMessage("CustomError")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Edit.cshtml, attention on @using same with Create.cshtml:

@model PersonEntity.Model.ProductPhoto

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Edit", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ProductPhoto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.File, new { type = "file" })
                @Html.ValidationMessage("CustomError")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PhotoFileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargePhoto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargePhoto, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargePhoto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargePhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargePhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargePhotoFileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ImageSize, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ImageSize, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

You may need to modify Web.config for larger file, add "maxRequestLength="2097152":

  <system.web>
    <globalization culture="auto" uiCulture="auto" />
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" maxRequestLength="2097152" />
  </system.web>

Have fun

Hi lolo512,

Thanks for your post.

According to your description,

lolo512

how can I upload an image and save the url in the database

Here is a sample,you can refer to the following code snippet:

table:

CREATE TABLE [dbo].[tblA]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [fname] NVARCHAR(50) NULL, 
    [lname] NVARCHAR(50) NULL, 
    [imageUrl] NVARCHAR(50) NULL
)
  • Creat an "Images" folder in Solution explorer.
  • Create an ADO.NET Entity Data Model (in this example is "Database1Entities") 
  • Home Controller: 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace test2.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        return View();
    }
    
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
    
        if (file != null)
        {
            Database1Entities db = new Database1Entities();
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath =Server.MapPath("~/images/"+ ImageName);
    
            // save image in folder
            file.SaveAs(physicalPath);
    
            //save new record in database
            tblA newRecord = new tblA();
            newRecord.fname = Request.Form["fname"];
            newRecord.lname = Request.Form["lname"];
            newRecord.imageUrl = ImageName;
            db.tblAs.Add(newRecord);
            db.SaveChanges();
    
        }
        //Display records
        return RedirectToAction("../home/Display/");
    }
    
    public ActionResult Display()
    {
        return View();
    }
    }
    }
  • Index View 

    @{
       ViewBag.Title = "Index";
    }
    
    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
    {
    <div>
    First name<br />
    @Html.TextBox("fname") <br />
    Last name<br />
    @Html.TextBox("lname") <br />
    Image<br />
    <input type="file" name="file" id="file" style="width: 100%;" /> <br />
    <input type="submit" value="Upload" class="submit" />
    </div>    
    }
  • Display View 

    @{
        ViewBag.Title = "Display";
    }
    
    @{
       test2.Database1Entities db = new test2.Database1Entities();
    }
    @using (Html.BeginForm())
    {
    <table border="1">
    <thead>
        <tr>
            <th>Image</th>
            <th>First name</th>
            <th>Last name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in db.tblAs)
        {
            <tr>
                <td><img src="~/images/@item.imageUrl" width="100" height="100" /></td>
                <td>@item.fname</td>
                <td>@item.lname</td>
            </tr>
        }
    </tbody>
    </table>
    }

Output:

/Home/ 

/home/Display/ 

More information:

http://forums.asp.net/t/1981336.aspx?Storing+Image+Url+in+Database

http://stackoverflow.com/questions/17499259/upload-a-picture-to-a-database-in-asp-mvc-4

Hope this can be helpful.

Best Regards,

Eileen

thank you for the reply it was very helpful. I need help in one more thing, instead of first and last name I have category which I am supposed to read from a database table category (ID-categoryName) and depending on the selected value the images is saved
in a folder of that selected value.

for example selected value :basketball.

the image path is: ~/basketball/fileName

can you help me with that??

[RESOLVED]Server.MapPath check for folder and create

I’m uploading an image to a folder images. it’s working fine.but what I actually want is to look for a folder name (I have the folder name) if not found create that folder and give it that name.how could that happen?

this is what I have done so far:

string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);

instead of images I should have folderName.

bool exists = System.IO.Directory.Exists(Server.MapPath(" YOUR PATH "));

if(!exists)
    System.IO.Directory.CreateDirectory(Server.MapPath(
" YOUR PATH "
));

Please try as this to check if the directory exists if not create.

Post back your queries if any.

Thanks :)

this is my upload function.please do edit:

public ActionResult FileUpload(HttpPostedFileBase file)
{

if (file != null)
{

string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);

// save image in folder
file.SaveAs(physicalPath);

//save new record in database
datum newRecord = new datum();
newRecord.category = Request.Form["category"];
newRecord.description = Request.Form["description"];
newRecord.imagePath = ImageName;
db.data.Add(newRecord);
db.SaveChanges();

}
//Display records
return RedirectToAction("Display");
}

public ActionResult FileUpload(HttpPostedFileBase file)
{

if (file != null)
{

string ImageName = System.IO.Path.GetFileName(file.FileName);
string dirPath = Server.MapPath("~/images/");
if(!System.IO.Directory.Exists(dirPath))
{
System.IO.Directory.CreateDirectory(dirPath);
}
string physicalPath = Server.MapPath("~/images/" + ImageName);

// save image in folder
file.SaveAs(physicalPath);

//save new record in database
datum newRecord = new datum();
newRecord.category = Request.Form["category"];
newRecord.description = Request.Form["description"];
newRecord.imagePath = ImageName;
db.data.Add(newRecord);
db.SaveChanges();

}
//Display records
return RedirectToAction("Display");
}

[RESOLVED]Frustrating MVC "404" error when trying to use Areas

This will (hopefully) be an easy one for an experienced MVC developer to solve.  It has me frustrated to death, however.  What am I missing?

I inherited an MVC project from a programmer whose last act was to separate it into Areas.  I’ve included a screen snapshot of the VS solution file below with the portions relevant to this description highlighted.  The problem I’m encountering is "404 not
found" errors when I try to use Html.ActionLink() to reference views in areas other than the one generating the link.  To start from scratch and isolate the problem, I’ve tried the following steps:

1. Create a new area by right-clicking the areas folder and "Add | Area"
2. Named the new area "DocumentUploaderNew"
3. Created a new controller by right-clicking DocumentUploaderNew and "Add | Controller"
4. I’ve named my new controller "FileUploadController"
5. Created a new view by right-clicking DocumentUploaderNew and "Add | View"
6. I’ve named my new view "FilerUploader.cshtml"

Now, in one of the other areas ("UserAccount") I have a view named "MyAccount.cshtml".  It contains two pieces of markup relevant to this problem:

          @Html.ActionLink("Upload Documents", "FileUploader", new { controller = "FileUpload", area = "DocumentUploaderNew" }, new { @class = "btn btn-info" })

and:

         @Html.ActionLink("Edit Questions", "ChangeQuestions", new { controller = "Account", area = "UserAccount" }, new { @class = "btn btn-info" })

The second link (to "ChangeQuestions") works perfectly.  The first (to "FileUploader") fails with the following error.  The only difference I can see is that for the working link, the reference is to a view within the same area as the "calling" page.  The
link that doesn’t work is to a view in a different area.  This seems like such a simple thing–and I’m sure it is–but I cannot find it.  Thanks in advance for any and all help.

The resource cannot be found.

Description:
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /CROMERR.Website/DocumentUploaderNew/FileUpload/FileUploader

do you have an FileUploader action in the FIleUpload controller?

Thank you for the reply ignatandrei.  I do, but stupid question: how does the action name in the controller relate to the name of the view (the .cshtml file)?  You may have pinned this down for me.  I had to do some renaming when I started trying to build
my workarounds of what the previous programmer left me.  Some of the names I chose were the obvious ones he picked, and MVC was barfing on name conflicts.  I wonder if I have messed something up in my renaming? 

Hi MarcAaron,

First, you need have a folder in the Views which name is the same as the controller name and the views should be in that folder or in Shared folder. So please put the view file (FileUploader.cshtml) to FileUpload folder.

Secondly, by default the view name should be the same as action name unless you specify the view name. (return View(“viewname”)

Best Regards

Starain

Thank you Starain.  It looks like that was the problem.  It looks like I got myself into a bind with the renaming… the previous programmer had already used the default view name elsewhere and MVC was barfing on that, so I had to give my .cshtml file a
different name.  I’ve started from scratch with some guaranteed unique names and all is well now.

I am unsure why the naming would be an issue across separate areas but, again, I am new to this and could be doing something wrong.  And/or, having inherited a broken project, perhaps there are some configuration issues the previous programmer left me to
deal with.  Regardless, it looks like I’m off and running again.  Thank you.

[RESOLVED]showing default image for user profile

Hi, in my project each user can save a picture for him/her profile.

now when a user log in I will show the user image and if the user has no profile image I will show an image in this url: "~/Images/default.png";

I’ve written this code. and i need help for else part to show the default image.

        public ActionResult GetProfilePhoto()
        {
            var image = (from u in db.UserProfiles
                         where u.UserName== User.Identity.Name
                         select u.Image).FirstOrDefault();
            if (image != null)
            {
                var stream = new MemoryStream(image.ToArray());
                return new FileStreamResult(stream, "image/jpeg");
            }
            else
            {

            }
        }

Hi,

You may convert a default image file from and set it in to variable "image".

            if (image != null)
            {
                var stream = new MemoryStream(image.ToArray());
                return new FileStreamResult(stream, "image/jpeg");
            }
            else
            {
               // convert a default image file from a folder to stream, and return the converted stream
            }

Or you can manipulate on .cshtml view like this:

            @if (item.Photo == null)
            {
                <img src="~/images/normal/defaultPhoto.png" width="50" />
            }
            else
            {
                <img src="data:image/png;base64,@Convert.ToBase64String(item.Photo, 0, item.Photo.Length)" width="50" />
            }

Have fun

how can i convert a default image file from a folder to stream

[RESOLVED]FileUpload With Progress

Hello,

I"m trying to upload a file while showing it’s progress.  The file uploads correctly but I can’t see to get the progress to show.  Any help would be greatly appreciated.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="BlogImages.aspx.cs" Inherits="Site_Admin.BlogImages" %>
<asp:Content ID="Content1" ContentPlaceHolderID="SiteHead" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="SiteContent" runat="server">
 <script type="text/javascript">
     function SetProgressBarProgressAmount(progress) {
         var progressBarId = 'progressBar';
         var percentageId = 'percentage';
         progressAmount = progress + 'px';
         percentageAmount = progress + '%';

         var progressDiv = document.getElementById(progressBarId);
         var percentageDiv = document.getElementById(percentageId);
         progressDiv.style.width = progressAmount;
         percentageDiv.innerHTML = "<p>" + percentageAmount + "</p>";
         alert("I am an alert box!!!!");
     }    
     function chooseFile() {
         document.getElementById("<%= FileUpload1.ClientID %>").click();
     }

    </script>
    <div style="height: 0px; overflow: hidden">
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </div>
    <div class="form_settings">
                <div style="border:2px solid" id="progressBar" runat="server">&nbsp;sdfsdf</div>
                <div style="border:2px solid" id="percentage" runat="server">&nbsp;sfsdf</div>
                <hr />
                <input class="submit" type="submit" id="btnBack" runat="server" value="Back" onserverclick="btnBack_Click" />
                <input class="submit" type="submit" id="btnUpload" runat="server" value="Upload" onserverclick="btnUpload_Click" onclick="chooseFile();" />                
        <asp:Table runat="server" ID="ImagesTable">
        </asp:Table>
    </div>
</asp:Content>

///C# Code

        public void setProgressBar(string ProgressAmount)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);

            StringBuilder sb = new StringBuilder();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "SetProgressBarProgressAmount('" + ProgressAmount + "')", true);
        }

        public void DownloadTheFileToServer(HttpPostedFile file, int id)
        {
            Stream stream = null;
            FileStream fs = null;

            try
            {
                string strFileName = System.IO.Path.GetFileName(file.FileName);
                int contentLength = file.ContentLength;
                stream = file.InputStream;
                long totalUploadSize = stream.Length;
                int bufferSize = 0;
                //less than 1kB
                if (totalUploadSize <= 1024)
                {
                    bufferSize = 1024;
                }
                //less than 4kB but more than 1kB
                else if (bufferSize <= 4096)
                {
                    bufferSize = 4096;
                }
                //less than 8Kb
                else if (bufferSize <= 8192)
                {
                    bufferSize = 8192;
                }
                else
                {
                    bufferSize = 16384;
                }

                byte[] b = new byte[1024];
                int tripDownloadSize = 0;
                long totalDownloadedSize = 0;
                float Percentage = 0;
                string fileStoreLocation = Server.MapPath("~/Site_Content/Images/Source/");
                fs = new FileStream(fileStoreLocation + strFileName, FileMode.Append);

                //Uplaods 8Kb at a time
                while ((tripDownloadSize = stream.Read(b, 0, 1024)) > 0)
                {
                    fs.Write(b, 0, tripDownloadSize);
                    totalDownloadedSize += tripDownloadSize;
                    Percentage = (int)(totalDownloadedSize * 100) / totalUploadSize;
                    setProgressBar(Percentage.ToString());
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception objException)
            {
                throw objException;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string dir = Server.MapPath("~/Site_Content/Images/");
                string file = DateTime.Now.ToString("MMddyyHHmmss");
                string ext = Path.GetExtension(FileUpload1.FileName);

                string SourceFile = Path.Combine(dir + "/Source/", FileUpload1.FileName);
                string OrigFile = Path.Combine(dir, file + ext);
                string OrigURL = "Site_Content/Images/" + file + ext;
                string ThumbFile = Path.Combine(dir, file + "_T" + ext);
                string ThumbURL = "Site_Content/Images/" + file + "_T" + ext;

                    DownloadTheFileToServer(FileUpload1.PostedFile, 0);

Hi JBryanB,

Thanks for your post.

Based on your description and code provided, I see you want to show the progress of uploading file.

As known that asp.net web form is based on http protocol with request-response communication model.

When you click the Button, page will do a postback and form post file stream to server side. Then page UI will not

be changed before server side behind code executes completed. So below method will not work.

JBryanB

public void setProgressBar(string ProgressAmount) { Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true); StringBuilder sb = new StringBuilder(); Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript",
"SetProgressBarProgressAmount(‘" + ProgressAmount + "’)", true); }

For how to show progress of uploading file, we usually do it in the client side (using javascript) please take a look at below:

http://www.codeproject.com/Articles/113418/ASP-NET-File-Upload-with-Progress-Bar

http://www.codeproject.com/Articles/26668/Showing-progress-bar-while-uploading-a-file-in-an

Thanks.

Best Regards

Hey,

Thanks for the reply.  That second example really cleared things up for me.

[RESOLVED]Client-Side File Size Check

I am using .NET 4.0, 4.5, VB.NET, and the asp:FileUpload functionality to upload a file from the client’s PC to my web server. Prior to actually doing the upload I need to verify that the file size is less than some limit that I set (Ex: 10240 KB).

I know that I can limit the file size in the web.config using the maxRequestLength parameter. However, if I set this parameter to 10240 and the client uploads a file larger than that, the application blows up with a very unfriendly message. I could set the
maxRequestLength to something greater than 10240 KB and then check the file size after it has been uploaded to see if it is less than 10240 KB, however there is still the possibility the client will submit a file larger than the maxRequestLength.

I need to check the file size from the client side prior to the upload, give the client a friendly message if the size is greater than whatever I want the maximum to be, and then prevent the upload from occurring.

Does anyone know how to do this?

 

=

Here is my JSfor this, using simple javascript you can check file size.  JSFiddle- http://jsfiddle.net/c6pz1huz/1/

<input type="file" id="fl"/>
<input type="button" value="check file size" onclick="Checksize();" />



function Checksize()
{
var k = document.getElementById("fl").files[0].size;
alert( "file size in KB " + k/1024 );
}

using jquery:

var fileSize = $('#your_upload_control').get(0).files[0].size;

This gets you the size in bytes, here’s a helper for formatting to your users:

//Method to format a files bytes
    function formatBytes(num) {

        if (num <= 1023) {
            return num + " bytes";
        }
        else if (num >= 1024 && num <= 1048575) {
            return Math.round(num / 1024) + " kb";
        }
        else {
            return Math.round(num / 1048576) + " mb"
        }

    }//end of formatBytes()

arindamnayak,

Maybe it is my limited knowledge of ASP.NET and VB.NET, but your solution does not seem to incorporate the use of the asp:FileUpload functionality. I am not certain how to implement your solution and the asp:FileUpload into a single solution.  

remojr76,

I have the same problem with your solution. How do I combine your solution with the asp:FileUpload?

I was saying that, you can use ID field of asp:fileupload in JS too!. I.e. following will work, i mean it is.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function checkfile()
        {
            var k = document.getElementById("fl").files[0].size;
            alert("file size in KB " + k / 1024);
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fl" runat="server" />
        <asp:Button ID="btncheck" runat="server" OnClientClick="return checkfile();" Text="Check" />
   </div>
    </form>
</body>
</html>

The asp:FileUpload functionality automatically generates a field (textbox for lack of a better term) and a Browse button. When you click on the Browse button you get a window which allows the user to locate (browse to) the file to be uploaded. When they
highlight that file and click "Open", the window closes and the file they specified is displayed in the field (textbox). It is at this moment that I need the client (in the code behind) to get the file size for the file, test it, and generate a message if
it is greater than whatever maximum I specify.

The asp:FileUpload does not have an OnChange event that would allow me to execute client side code to check the file size.

The code you sent me creates a separate button which the user must click or I have to find some way of executing the code behind automatically. I don’t want to rely on the user to click on this button. The Upload button (see the btnUpLoad_Click code behind
that is below) runs on the server and therefore cannot do the file size check until after the file has already been uploaded. 

 I do not understand exactly when the upload (file transfer from the client to the server) is performed. Does it happen upon completion of the Browse functionality when the file name is placed in the field (textbox) or does it happen when the FileUpload.SaveAsFile
statement (in the code below) is executed on the server? The following code is the OnClick event tied to an asp:Button which follows the asp:FileUpload.

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        'This sub comes from //www.dotnetbull.com/2013/03/how-to-upload-file-in-aspnet-using.html
        Debug.Print(Now() & " " & "FileUpload/FileUploadId.aspx, btnUpload_Click")

        Dim strFileSavePath As String
        Dim fileName As String = FileUpload.PostedFile.FileName
        Debug.Print(Now() & " " & "fileName=" & fileName)

        Dim fileExtension As String = System.IO.Path.GetExtension(fileName)
        Debug.Print(Now() & " " & "fileExtension=" & fileExtension & "|")

        Dim fileMimeType As String = FileUpload.PostedFile.ContentType
        Debug.Print(Now() & " " & "fileMimeType=" & fileMimeType & "|")

        Dim intfileLengthInKB As Integer = Math.Ceiling(FileUpload.PostedFile.ContentLength / 1024)
        Dim intfileLengthInMB As Integer = Math.Ceiling(intfileLengthInKB / 1024)
        Debug.Print(Now() & " " & "fileLengthInKB=" & intfileLengthInKB)

        Dim maxintfileLengthInKB As Integer = 10240    'max filesize = 10MB = 10240KB 
        Dim maxintfileLengthinMB As Integer = maxintfileLengthInKB / 1024
        Debug.Print(Now() & " " & "maxintfileLengthInKB=" & maxintfileLengthInKB)

        'The matchExtension and matchMimeType values come from 
        ' //www.telerik.com/help/aspnet-ajax/upload-mime-types.html
        Dim matchExtension As String = ".xls .xlsx"

        Dim matchMimeType As String = "application/excel application/vnd.ms-excel application/x-excel application/x-msexcel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

        If FileUpload.HasFile Then
            Debug.Print(Now() & " " & "HERE 1")
            Debug.Print(Now() & " " & "matchExtension.Contains(fileExtension)=" & matchExtension.Contains(fileExtension))
            Debug.Print(Now() & " " & "matchExtension.Contains(fileMimeType)=" & matchExtension.Contains(fileMimeType))
            If matchExtension.Contains(fileExtension) And matchMimeType.Contains(fileMimeType) Then
                Debug.Print(Now() & " " & "HERE 2")
                If intfileLengthInKB <= maxintfileLengthInKB Then
                    Debug.Print(Now() & " " & "HERE 3")
                    Try

                        Debug.Print(Now() & " " & "HERE 4")
                        If Me.Session("ProdTestServer") = "Prod" Then
                            strFileSavePath = "\CHEROKEE"
                        Else
                            strFileSavePath = "\dakotaishardingUploadedFiles"        'FOR TESTING
                            'strFileSavePath = "c:appsOnlineAgentData"        'FOR TESTING
                        End If
                        Debug.Print(Now() & " " & "strFileSavePath=" & strFileSavePath)

                        Dim strFileNameAtHCAD = "OAS_P_" & Session("gstr_v_Agent") & "_" & _
                                          DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") & "_" & _
                                          FileUpload.FileName
                        Dim strSaveAsFile = strFileSavePath & strFileNameAtHCAD
                        Debug.Print(Now() & " " & "FileUpload.SaveAs=" & strSaveAsFile)

                        FileUpload.SaveAs(strSaveAsFile)
                        lbl_FileUploadMsg11.Text = "File Name: "
                        lbl_FileUploadMsg12.Text = FileUpload.PostedFile.FileName
                        lbl_FileUploadMsg21.Text = "File Size: "
                        lbl_FileUploadMsg22.Text = intfileLengthInKB & " kb"
                        lbl_FileUploadMsg31.Text = "File Extension: "
                        lbl_FileUploadMsg32.Text = fileExtension
                        lbl_FileUploadMsg41.Text = "Mime Type: "
                        lbl_FileUploadMsg42.Text = FileUpload.PostedFile.ContentType
                        lbl_FileUploadMsg51.Text = "HCAD Filename Is: "
                        lbl_FileUploadMsg52.Text = strFileNameAtHCAD
                    Catch ex As Exception
                        lbl_FileUploadMsg11.Text = "ERROR:"
                        lbl_FileUploadMsg12.Text = ex.Message.ToString()
                        lbl_FileUploadMsg21.Text = ""
                        lbl_FileUploadMsg22.Text = ""
                        lbl_FileUploadMsg31.Text = ""
                        lbl_FileUploadMsg32.Text = ""
                        lbl_FileUploadMsg41.Text = ""
                        lbl_FileUploadMsg42.Text = ""
                        lbl_FileUploadMsg51.Text = ""
                        lbl_FileUploadMsg52.Text = ""
                    End Try
                    Response.Write("File Uploaded Successfully")
                Else
                    lbl_FileUploadMsg11.Text = "ERROR: "
                    lbl_FileUploadMsg12.Text = "Maximum upload file size is " & maxintfileLengthInKB & " KB (" & maxintfileLengthinMB & " MB). Your file size is " & intfileLengthInKB & " KB (" & intfileLengthInMB & " MB)."
                    lbl_FileUploadMsg21.Text = ""
                    lbl_FileUploadMsg22.Text = ""
                    lbl_FileUploadMsg31.Text = ""
                    lbl_FileUploadMsg32.Text = ""
                    lbl_FileUploadMsg41.Text = ""
                    lbl_FileUploadMsg42.Text = ""
                    lbl_FileUploadMsg51.Text = ""
                    lbl_FileUploadMsg52.Text = ""
                End If
            Else
                lbl_FileUploadMsg11.Text = "Informational: "
                lbl_FileUploadMsg12.Text = "Please select only .xls or .xlsx files."
                lbl_FileUploadMsg21.Text = ""
                lbl_FileUploadMsg22.Text = ""
                lbl_FileUploadMsg31.Text = ""
                lbl_FileUploadMsg32.Text = ""
                lbl_FileUploadMsg41.Text = ""
                lbl_FileUploadMsg42.Text = ""
                lbl_FileUploadMsg51.Text = ""
                lbl_FileUploadMsg52.Text = ""
            End If
        Else
            lbl_FileUploadMsg11.Text = "Informational: "
            lbl_FileUploadMsg12.Text = "You have not specified a file."
            lbl_FileUploadMsg21.Text = ""
            lbl_FileUploadMsg22.Text = ""
            lbl_FileUploadMsg31.Text = ""
            lbl_FileUploadMsg32.Text = ""
            lbl_FileUploadMsg41.Text = ""
            lbl_FileUploadMsg42.Text = ""
            lbl_FileUploadMsg51.Text = ""
            lbl_FileUploadMsg52.Text = ""
        End If

    End Sub

 

I just tested this and it works:

<div>

        <asp:FileUpload ID="myUpload" ClientIDMode="Static" runat="server" />
    
    </div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script>

        $(function () {

            $('#myUpload').change(function () {

                alert($(this).get(0).files[0].size);

            });

        });
        

    </script>

Hope it helps!

I have tried the following without success:

                var filesize = $(this).get(0).files[0].size;
                var filesize = $('#MainContent_FileUpload').get(0).files[0].size;

When I use either one of the above lines of code I get the following message:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

Using the $(‘#MainContent_FileUpload’).val() is am able to get the name of the file to be uploaded.

Below is the jscript code I am using, along with various lines of code that attempt to get the file size. None of them work. The code that gets fileName does work.

    <script type="text/jscript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script type="text/jscript">

        $(function () {
            //alert("I AM HERE 1 !!");
            $('#MainContent_FileUpload').change(function () {
                alert("I AM HERE 2 !!");

                var objFileUpload = $('#MainContent_FileUpload')
//                var fileName = $('#MainContent_FileUpload').val();
                var fileName = objFileUpload.val();
                alert('fileName : ' + fileName);

//                var fileSize = $('#MainContent_FileUpload').size.val();
//                var fileSize = $('#MainContent_FileUpload').files[0].size;
//                var fileSize = $('#MainContent_FileUpload').files[1].size();
//                var filesize = $('#MainContent_FileUpload').files.size;
//                var fileSize = this.files[0].size;
//                var filesize = this.files.size;
//                var fileSize = document.files[0].size;
//                var filesize = document.files.size;
//                var fileSize = objFileUpload.files[1].size();
//                var filesize = $(this).get(0).files[0].size;
                var filesize = $('#MainContent_FileUpload').get(0).files[0].size;
                alert('fileSize : ' + fileSize);

//                var fileSize = $('#MainContent_FileUpload').files[0].size;
//                var fileType = $('#MainContent_FileUpload').files[0].type;
//                alert('FileName : ' + fileName + 'nFileSize : ' + fileSize + ' bytes');
//                //alert($(this).get(0).files[0].size);

            });

        });
    </script>

Does anyone have any other suggestions?

What is the name of your File Upload control? Best not to name if FileUpload since that’s already the name of the class. When referencing a control, you need to get it’s client id property. ASP.Net will generate a unique id for each control based on it’s
position in the control tree.

Try:

$('#<%= ControlName.ClientID %>')

This is a tricky control to work with client-side. The FIleUpload control actually isn’t rendering a field and a button, all it does is emit a file input control. <input type="file" > That’s all it does on that side really. It does a lot more though on the
server side to help you deal with the upload. The browsers and W3C keep the file input element sparse as far as what you can do with it to avoid it from becoming a security issue. Example: what would happen if you could set the filename, then you could swap
the user selected file for another more sensitive filename without them knowing. That’s one of the reasons it’s fairly tricky. Also, a lot of the features for doing things such as determining file size only work in newer browsers due to advances in HTML5.

markfitzme,

As you recommended I have renamed all references to my File Upload control to FileUploadToOAS.

I was not certain where to use the $("#… code you suggested so my first attempt was:

                var filesize = $('#<%= FileUploadToOAS.ClientID %>').get(0).files[0].size;
                alert('fileSize : ' + fileSize);

I am still getting the error message:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

on the "var filesize =…" statement.

Do you have any further suggestions?

Is the File upload control ClientIDMode set to Static?

  <asp:FileUpload ID="myUpload" ClientIDMode="Static" runat="server" />

 

remojr76,

Yes

<asp:FileUpload ID="FileUploadToOAS" Width="100%" ClientMode="Static" runat="server" />

you can use like this.

var filesize = $('#<%= FileUploadToOAS.ClientID %>').files[0].size;
                alert('fileSize : ' + fileSize);

arindamnayak,

Your suggestion did not work.

Please see my jscript below.

Note the runtime errors that were generated for each of the attempts at getting the file size occurred on the line of code indicated except for the "//JavaScript runtime error: ‘fileSize’ is undefined" error which occurred on the "alert(‘fileSize
: ‘
+ fileSize);" statement.

    <script type="text/jscript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script type="text/jscript">

        $(function () {
            //alert("I AM HERE 1 !!");
            $('#MainContent_FileUploadToOAS').change(function () {
//                alert("I AM HERE 2 !!");

                var objFileUploadToOAS = $('#MainContent_FileUploadToOAS')
//                var fileName = $('#MainContent_FileUploadToOAS').val();
                var fileName = objFileUploadToOAS.val();
//                alert('fileName : ' + fileName);

//                var fileSize = $('#MainContent_FileUploadToOAS').size.val();                  //JavaScript runtime error: Object doesn't support property or method 'val'
//                var fileSize = $('#MainContent_FileUploadToOAS').files[0].size;               //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var fileSize = $('#MainContent_FileUploadToOAS').files[1].size();             //JavaScript runtime error: Unable to get property '1' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').files.size;                  //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var filesize = MainContent_FileUploadToOAS.PostedFile.ContentLength;          //JavaScript runtime error: 'MainContent_FileUploadToOAS' is undefined
//                var filesize = objFileUploadToOAS.PostedFile.ContentLength;                   //JavaScript runtime error: Unable to get property 'ContentLength' of undefined or null reference
//                var fileSize = this.files[0].size;                                            //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = this.files.size;                                               //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var fileSize = document.files[0].size;                                        //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = document.files.size;                                           //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var fileSize = objFileUploadToOAS.files[1].size();                            //JavaScript runtime error: Unable to get property '1' of undefined or null reference
//                var filesize = $(this).get(0).files[0].size;                                  //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).files[0].size;        //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#<%= FileUploadToOAS.ClientID %>').get(0).files[0].size;    //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).size;                 //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').get(0);                      //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').size;                        //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').size();                      //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).size();               //JavaScript runtime error: Function expected
                var filesize = $('#<%= FileUploadToOAS.ClientID %>').files[0].size;             //JavaScript runtime error: Unable to get property '0' of undefined or null reference

                alert('fileSize : ' + fileSize);

//                var fileSize = $('#MainContent_FileUploadToOAS').files[0].size;
//                var fileType = $('#MainContent_FileUploadToOAS').files[0].type;
//                alert('FileName : ' + fileName + 'nFileSize : ' + fileSize + ' bytes');
//                //alert($(this).get(0).files[0].size);

            });

        });
    </script>

I have tried following , and it is working as expected. Note: your JS is wrong, as JS is case sensitive , if you have "var filesize " and later use "fileSize", it will not work, rather error will be shown.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script type="text/javascript" >
        function onfilechange() {
            var fileSize = document.getElementById("<%= FileUploadToOAS.ClientID %>").files[0].size;
            alert('fileSize : ' + fileSize);
        }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
    </div>
        <asp:FileUpload ID="FileUploadToOAS" runat="server" onchange="onfilechange();"/>
        
    </form>
</body>

</html>

arindamnayak,

Is the onfilechange function executed on the server or on the client?

If it is executed on the server that means that the file must be uploaded before the filesize can be checked. I want the filesize checked before the upload occurs so that the user is prevented from uploading a file larger than the maximum I have specified
in my web.config file.

Additionally:

When I tried your suggestion using the onchange attribute with the asp:FileUpLoad I get the following message:

Message 3 Validation (ASP.Net): Attribute ‘onchange’ is not a valid attribute of element ‘FileUpload’. C:Online Agent ServicesOASv2-2FileUploadFileUploadId.aspx 158 106 C:Online Agent ServicesOASv2-2

I tried running with the above error anyway and got the following message in the onfilechange function on the line where it is setting the var filesize =:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

I am still looking for a solution to the problem of client-side file size check. None of the suggestions above have worked.

Thanks.

All i can say is, it is working for me, and onchange is  JS attribute, that might not get detected by VS. So finally you are getting JS error.

If you put the code i had given in an ASPX and browse, check view source, you will get the following

<input
type
="file"
name
="FileUploadToOAS" id="FileUploadToOAS"
onchange="checkfile();" />

i.e. it translates to simple input type file, so it should work.

Can you do rightclick-view source and paste that specific HTML here.

arindamnayak,

The asp:FileUpload functionality generates an input type="file" as you indicated. However, it also generates a browse button which, when clicked, opens a window allowing the user to browse to the file on their network to be uploaded. The "onchange=" event
gets a "Validation (ASP.Net): Attribute ‘onchange’ is not a valid attribute of element ‘FileUpload’" message in the Error List.

Below is the code generated as seen in the "View Source":

                                <tr>
                                    <td colspan="1" align="right"  style="width:15%; padding-right:5px;">
                                        <span id="MainContent_Label15" style="display:inline-block;color:Black;width:100%;">File :</span>
                                    </td>
                                    <td colspan="1" align="left" style="width:85%; text-align:left; padding-top:0px;" >
                                        <input type="file" name="ctl00$MainContent$FileUploadToOAS" id="MainContent_FileUploadToOAS" onchange="CheckFileSize()" style="width:100%;" />
                                        
                                        
                                    </td>
                                </tr>

Below is the CheckFileSize function:

    <script type="text/javascript" >
        function CheckFileSize() {
            var fileSize = document.getElementById("MainContent_FileUploadToOAS").files[0].size;
            alert('CheckFileSize, fileSize : ' + fileSize);
        }
    </script>

It’s not really generating a button. The browser does that for an input type=file, not HTML or ASP.Net. ASP.Net won’t allow onchange because it’s not a supported property. You can add it in codebehind though like so:

if(!Page.IsPostBack)
{FileUploadToOAS.Attributes.Add("onchange","CheckFileSize()");}

Hi,

Have you tried the http://jsfiddle.net/c6pz1huz/1/ Fiddle posted earlier? Does it work with your browser?

What is the browser you are using to test suggestions which are made?

With the code you have give, it should work. Yes, VS might show warning  that, onchange is not valid, But JS work this way only. If that is not working, there can be some JS error , you are getting in browser, can you post those error, or  "CheckFileSize",
is not invoked at all?