Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a Ajax/JQuery upload of an image in ASP.NET MVC?

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

like image 427
Brian Hvarregaard Avatar asked Mar 11 '11 11:03

Brian Hvarregaard


2 Answers

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.

like image 149
LeftyX Avatar answered Sep 28 '22 18:09

LeftyX


You could use a JQuery Form plugin. You can find the code and examples here:

http://jquery.malsup.com/form/#file-upload

Hope this helps.

like image 24
Zack Avatar answered Sep 28 '22 20:09

Zack