0

在客户端我需要保存图像,用户只能通过输入选择文件(类型=文件)。

  1. 我想在不更新页面的情况下保存,或回发。
  2. 我使用页面方法保存其他数据,我收集所有内容并转换为 Json 并通过页面方法发送。是否可以将图像与其他数据一起保存?
  3. 我必须通过 IE(少于 10 个)工作,所以我不能使用 html 5。
  4. 我找到了一些 jQuery 插件,但我无法在 asp.net 中使用它们。他们通常调用php服务器端。
  5. 我也很难从 SQL Server 中读取保存图像。
  6. 如果我在客户端获取图像,转换为 json,然后发送然后转换为字节并保存在 SQL Server 中,那就太好了
4

2 回答 2

0

文件上传需要完整的回发。使用隐藏的 iframe/form 进行回发以将文件上传到服务器。

下面是示例代码。

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);
            }
        });
    }
}

控制器

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);
}

公共输出类

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

不要忘记包含 Ajax-Form js 文件 ( https://github.com/garagesocial/ajax-form-js )

于 2013-10-15T04:58:53.920 回答
0

在更新面板中使用回帖请参阅此链接以获取有关更新面板的更多信息 http://msdn.microsoft.com/en-us/library/bb399001.aspx

于 2013-10-15T05:21:11.187 回答