怎样进行的Ajax / JQuery的上传在ASP.NET MVC的形象? [英] How do I perform a Ajax/JQuery upload of an image in ASP.NET MVC?

查看:141
本文介绍了怎样进行的Ajax / JQuery的上传在ASP.NET MVC的形象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写在ASP.NET MVC的网站。我有一个页面,用户可以创建一个小文章。为了这篇文章,他们可以选择图像。我有一个页面,在这里他们可以上传自己的照片和创建文章页面,只需列出它们。但是很多人都在抱怨,他们已经意识到,他们没有上传他们所需要的图像之前写了整篇文章。我要的是为用户能够上传从创建文章页面图像,然后重新装入我可能图像从下拉菜单中选择。

即时通讯思想在页面上制作一个单独的多部分的形式,并让用户选择有一个文件(主要使用现有的上传功能)。但是,我怎么去围绕在提交异步?又有怎样的形象异步重新渲染我的列表?

如何使用jQuery / AJAX我上传此图片,然后重新填充我的下拉?

/欢呼声

解决方案

我用这个 jQuery的pluging 数次。
我把一个 jQuery UI的模态对话框它使用的 PopupImageUploader 元素我的上传按钮。

 < D​​IV ID =PopupImageUploader称号=上传图片>
    < D​​IV ID =uploaderFile>< / DIV>
< / DIV>
 

和我的javascript构建上传的元素 upladerFile

 函数CreateImageUploader(){
    VAR上传=新qq.FileUploader({
        元件:$('#uploaderFile')[0],
        模板:'< D​​IV CLASS =QQ-上传> +
                              '< D​​IV CLASS =QQ上传拖放区><跨度>文件拖放此处进行上传< / SPAN>< / DIV> +
                              '< D​​IV CLASS =QQ上传按钮的UI按钮的UI控件界面角,所有的用户界面键式的纯文本用户界面状态默认> Seleziona IL Listino的Excel< / DIV> +
                              '< UL类=QQ上传列表>< / UL> +
                              '< / DIV>',
        hoverClass:UI状态悬停,
        focusClass:UI状态对焦,
        动作:首页/ UploadImage',
        allowedExtensions:JPG,GIF]
        PARAMS:{},
        的onsubmit:功能(文件,EXT){

            },
        的onComplete:功能(ID,文件名,responseJSON){
            $(#PopupImageUploader)对话框(亲密)。
            }
        }
    });
}
 

您可以使用的onComplete 事件查看上传的结果,最终,更新您的下拉。 您的 UploadImage 操作可以接收在 PARAMS指定额外的参数:{} 属性。 这是我的控制器:

  [HttpPost()]
    公共System.String UploadImage(串号)
    {

        布尔IsIE = FALSE;
        字符串sFileName =;
        变种TempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory_temp);

        如果((Request.Files == NULL)||(Request.Files.Count == 0))
        {
            如果(string.IsNullOrEmpty(Request.Params [qqfile]))
            {
                返回({成功:虚假,错误:请求文件是空的'});
            }
            其他
            {
                。sFileName = Request.Params [qqfile]的ToString();
            }
        }
        其他
        {
            sFileName = Request.Files [0] .FileName;
            IsIE =真;
        }

        如果(string.IsNullOrEmpty(sFileName))
        {
            返回({成功:虚假,错误:请求文件是空的'});
        }

        字符串DocumentName = ID + Path.GetExtension(sFileName);

        如果(IsIE)
        {
            尝试
            {
                Request.Files [0] .SaveAs(Path.Combine(TempFolder,DocumentName));
            }
            赶上(例外前)
            {
                返程({成功:虚假,错误:+ ex.Message +'});
            }
        }
        其他
        {
            尝试
            {
                如果((Request.InputStream =空)及!及(Request.InputStream.CanRead)及及(Request.InputStream.Length大于0))
                {
                    使用(的FileStream FILESTREAM =新的FileStream(Path.Combine(TempFolder,DocumentName),FileMode.Create))
                    {
                        byte []的FileBytes =新的字节[Convert.ToInt32(Request.InputStream.Length)+ 1];
                        的Int32读取动作= 0;
                        读取动作= Request.InputStream.Read(FileBytes,0,FileBytes.Length);
                        fileStream.Write(FileBytes,0,读取动作);
                        fileStream.Flush();
                        fileStream.Close();
                    }
                }
            }
            赶上(例外前)
            {
                返程({成功:虚假,错误:+ ex.Message +'});
            }
        }

        VAR newFileName =新分配的文件名;

        返程({成功:真,newfilename:+ newFileName +'});

    }
 

IE浏览器有不同的行为,所以我有两个不同的程序来读取文件。<​​/ P>

I have a site written in ASP.NET MVC. I have a page where the user can create a small article. To this article they can choose an image. I have a page where they can upload their images and on the create article page, simply list them. But many people are complaining that they have written an entire article before realizing that they dont have uploaded the image they need. What i want is for the user to be able to upload an image from the create article page, and then reload my dropdown of possible images to select from.

Im thinking on making a seperate multipart form on the page, and letting the user select a file there (basically use my existing upload functionality). But how do i go around submitting it async? And how about re-rendering my list of images async?

How do i upload this image using jquery/ajax, and then repopulate my dropdown?

/cheers

解决方案

I've used this jQuery pluging a few times.
I put my upload button in a jQuery UI modal dialog which uses the PopupImageUploader element.

<div id="PopupImageUploader" title="Upload Image">
    <div id="uploaderFile"></div>
</div>

and my javascript builds the uploader on the element upladerFile

function CreateImageUploader() {
    var uploader = new qq.FileUploader({
        element: $('#uploaderFile')[0],
        template: '<div class="qq-uploader">' +
                              '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                              '<div class="qq-upload-button ui-button ui-widget ui-corner-all ui-button-text-only ui-state-default">Seleziona il Listino Excel</div>' +
                              '<ul class="qq-upload-list"></ul>' +
                              '</div>',
        hoverClass: 'ui-state-hover',
        focusClass: 'ui-state-focus',
        action: 'Home/UploadImage',
        allowedExtensions: ['jpg', 'gif'],
        params: { },
        onSubmit: function(file, ext) {

            },
        onComplete: function(id, fileName, responseJSON) {
            $("#PopupImageUploader").dialog('close');
            }
        }
    });
}

You can use the onComplete event the check the result of the upload and, eventually, update your dropdown. Your UploadImage action can receive extra-parameters specified in the params: { } property. This is my controller:

    [HttpPost()]
    public System.String UploadImage(string id)
    {

        bool IsIE = false;
        string sFileName = "";
        var TempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_TEMP");

        if ((Request.Files == null) || (Request.Files.Count == 0))
        {
            if (string.IsNullOrEmpty(Request.Params["qqfile"]))
            {
                return ("{success:false, error:'request file is empty'}");
            }
            else
            {
                sFileName = Request.Params["qqfile"].ToString();
            }
        }
        else
        {
            sFileName = Request.Files[0].FileName;
            IsIE = true;
        }

        if (string.IsNullOrEmpty(sFileName))
        {
            return ("{success:false, error:'request file is empty'}");
        }

        string DocumentName = id + Path.GetExtension(sFileName);

        if (IsIE)
        {
            try
            {
                Request.Files[0].SaveAs(Path.Combine(TempFolder, DocumentName));
            }
            catch (Exception ex)
            {
                return ("{success:false, error:'" + ex.Message + "'}");
            }
        }
        else
        {
            try
            {
                if ((Request.InputStream != null) && (Request.InputStream.CanRead) && (Request.InputStream.Length > 0))
                {
                    using (FileStream fileStream = new FileStream(Path.Combine(TempFolder, DocumentName), FileMode.Create))
                    {
                        byte[] FileBytes = new byte[Convert.ToInt32(Request.InputStream.Length) + 1];
                        Int32 bytesRead = 0;
                        bytesRead = Request.InputStream.Read(FileBytes, 0, FileBytes.Length);
                        fileStream.Write(FileBytes, 0, bytesRead);
                        fileStream.Flush();
                        fileStream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                return ("{success:false, error:'" + ex.Message + "'}");
            }
        }

        var newFileName = "new assigned filename";

        return ("{success:true, newfilename: '" + newFileName + "'}");

    }

IE has a different behavior so I have two different procedures to read the file.

这篇关于怎样进行的Ajax / JQuery的上传在ASP.NET MVC的形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆