开发者

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


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.


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.


   <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜