0

On the client side I need to save an image, user only select file by input (type=file).

  1. I want to save without page fresh, or post back.
  2. I use page method to save other data, I collect everything and convert to Json and send by page method. Is it possible to save image with other data?
  3. I must work by IE (less than 10), so I can't use html 5.
  4. I found some jQuery plugin but I can't use them in asp.net. They usually call php server side.
  5. It's difficult for me to read in save image from SQL Server too.
  6. It would be great if I get image in client, convert to json, and send then convert to byte and save in SQL Server
7
  • What is your question exactly? Do you have sample code?
    – codemonkeh
    Commented Oct 15, 2013 at 3:56
  • Please try with the AsyncFileUpload. asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/… Commented Oct 15, 2013 at 4:12
  • use Jquery Uploadify ..................
    – Ram Singh
    Commented Oct 15, 2013 at 4:57
  • @codemonkeh i don't have sample code, but infact i can upload and save file after postback. but in this case i need upload and save without postback. Commented Oct 15, 2013 at 5:11
  • @raman uploadify (uploadify.com) as i check is html5, and i need to work by ie 7,8,9. Commented Oct 15, 2013 at 5:21

2 Answers 2

0

use post back inside an update panel please refer this link for more about update panel http://msdn.microsoft.com/en-us/library/bb399001.aspx

0

File upload needs a full postback. use hidden iframe/form to do the postback to upload the file to the server.

Below is the sample code.

HTML

<input type="file" size="15" name="file" onchange="UploadPicture(this, 'user-picture-form');" class="upload-new-avatar"/>

<img id="Myimg" src="" />

JavaScript

function UploadPicture(sender, form) {
    var newForm = $("<FORM>");
    newForm.attr({ method: "POST", enctype: "multipart/form-data" }).hide();
    newForm.appendTo($("body"));

    var $this = $(sender), $clone = $this.clone();
    $this.after($clone).appendTo($(newForm));

    AjaxFormSubmit({
        type: "POST",
        validate: false,
        parentControl: $(newForm),
        form: $(newForm),
        messageControl: null,
        throbberPosition: { my: "left center", at: "right center", of: sender, offset: "5 0" },
        url: '/Home/UploadPicture',
        success: function (data) {            
            if (data.Status == ActionStatus.Successfull) {
                if (data.Results == null || data.Results == 'null') {
                    //Message(data.Message, ActionStatus.Error);
                }
                else {
                    $("#Myimg").attr("src", "/Images/" + data.Results[0]);                    
                }
            }
            else {
                //Message(data.Message, ActionStatus.Error);                
            }
        }
    });
}

function AjaxFormSubmit(parameters) {
    /*=====================================Sample Usage======================================================
    AjaxFormSubmit({
    type: "POST",                                                                                       //default is "POST"
    validate: true,                                                                                     //if the form/data needs to be validated
    validationError: function () { },                                                                   //called only if validate is true
    parentControl: $(selector),                                                                         //required if validate is true
    error: function () { },                                                                             //called when an unexpected error occurs
    form:  $(selector),                                                                                 //neglected if data is not null
    data: {name: "value"}                                                                               //overwrites the form parameter
    messageControl:  $(selector),                                                                       //the control where the status message needs to be displayed
    beforeSubmit: function (arr, $form, options) { },                                                   //called before the form is actually submitted 
    throbberPosition: { my: "left center", at: "right center", of: sender, offset: "5 0" },             //the position at which the throbber needs to be displayed 
    url: url,                                                                                           //the url that needs to be hit
    success: function (data) {},                                                                        //called after the request has been executed without any unhandeled exception
    bar: $('.bar'),                                                                                     //var bar = $('.bar');
    percent: $('.percent'),                                                                             //var percent = $('.percent');
    status: $('#status')                                                                                //var status = $('#status');
    });
    ===============================================================================================*/

    if (parameters.validate == true) {
        if (ValidateControls($(parameters.messageControl), $(parameters.parentControl)) == false) {
            if (parameters.validationError) parameters.validationError();
            return false;
        }
    }
    if (parameters.data == undefined) {
        $(parameters.form).ajaxForm({
            url: parameters.url,
            dataType: $.browser.msie ? "json" : undefined,
            type: parameters.type == undefined ? "POST" : parameters.type,
            error: function () {
                RemoveThrobber();
                Message("Unexpected Error", ActionStatus.Error);
                if (parameters.error != undefined) parameters.error();
            },
            beforeSubmit: function (arr, form, options) {
                arr = NeglectWaterMark(arr, form);
                if (parameters.beforeSubmit) parameters.beforeSubmit(arr, form, options);
            },
            beforeSend: function () {
                if (parameters.status != null && parameters.status != undefined) {
                    parameters.status.empty();
                    var percentVal = '0%';
                    parameters.bar.width(percentVal)
                    parameters.percent.html(percentVal);
                }
            },
            uploadProgress: function (event, position, total, percentComplete) {
                var percentVal = percentComplete + '%';
                parameters.bar.width(percentVal)
                parameters.percent.html(percentVal);
            },
            success: function (data) {
                //RemoveThrobber();
                if (data.Status == undefined) {
                    Message('Invalid data returned in the response', ActionStatus.Error);
                    return false;
                }
                else if (parameters.bar!=null) {
                    var percentVal = '100%';
                    parameters.bar.width(percentVal)
                    parameters.percent.html(percentVal);
                    parameters.success(data);
                }
                else{
                parameters.success(data);
                }
            },
            complete: function (xhr) {

            }
        }).submit();
    }
    else {
        $.ajax({
            url: parameters.url,
            type: parameters.type == undefined ? "POST" : parameters.type,
            error: function (a, b, c) {
                RemoveThrobber();
                Message($(parameters.messageControl), "Unexpected Error", ActionStatus.Error);
                if (parameters.error != undefined) parameters.error();
            },
            async: true,
            data: parameters.data,
            success: function (data) {
                RemoveThrobber();
                if (data.Status == undefined) {
                    Message($(parameters.messageControl), "Invalid data returned in the response", ActionStatus.Error);
                    return false;
                }
                else {
                    parameters.success(data);
                }
            },
            error: function (obj) {
                Message(data.Message, ActionStatus.Error);
            }
        });
    }
}

Controller

public JsonResult UploadPicture(HttpPostedFileBase file)
{
    string newFilename = Guid.NewGuid().ToString() + "." + file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
    string fileExt = System.IO.Path.GetExtension(file.FileName).ToLower();

    ActionOutput result;
    if (fileExt == ".jpeg" || fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".png")
    {
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(file.InputStream);
        if (bitmap.Height > 600 || bitmap.Height < 200)
        {
            if ((Request.Browser).Browser == "IE")
                return Json(new ActionOutput { Status = ActionStatus.Error, Message = "Image must be between 200x200 to 600x600 pixel." }, "text/plain", JsonRequestBehavior.AllowGet);
            else
                return Json(new ActionOutput { Status = ActionStatus.Error, Message = "Image must be between 200x200 to 600x600 pixel." }, JsonRequestBehavior.AllowGet);
        }
        // Saving Image to Folder
        string folder = Server.MapPath("~/Images/");
        if (!System.IO.Directory.Exists(folder))
            System.IO.Directory.CreateDirectory(folder);
        file.SaveAs(folder + newFilename);
        result = new ActionOutput { Status = ActionStatus.Successfull, Results = new List<string> { newFilename } };
    }
    else
    {
        result = new ActionOutput { Status = ActionStatus.Error, Message = "Invalid file, valid file are *.jpg, *.jpeg, *.gif, *.bmp, *.png" };     
    }
    if ((Request.Browser).Browser == "IE")
        return Json(result, "text/plain", JsonRequestBehavior.AllowGet);
    else
        return Json(result, JsonRequestBehavior.AllowGet);
}

Common Output Class

public class ActionOutput
{
    public ActionStatus Status { get; set; }
    public String Message { get; set; }
    public List<String> Results { get; set; }
}

Don't forget to include Ajax-Form js file (https://github.com/garagesocial/ajax-form-js)

20
  • is it a tutorial or sample code. i heared this solution but can't find complete refrence. Commented Oct 15, 2013 at 5:09
  • @MohammadAdibi: Check this out. (I am assuming that you are using MVC .net) Commented Oct 15, 2013 at 5:26
  • unfortunately no, but i am trying do test it. Commented Oct 15, 2013 at 5:54
  • In that case, you should change UploadPicture method only which i have written in controller. Commented Oct 15, 2013 at 6:03
  • how to declare controller and common output class, i convert them to vb, put controller in code behind and common output as a class, but i receive many errors. Commented Oct 15, 2013 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.