How to upload image in ASP.NET MVC 4 using ajax or any other technique without postback?

前端 未结 7 1739
鱼传尺愫
鱼传尺愫 2020-12-05 05:40

I am developing a website in MVC 4, where user fill some information and save it to upload. all the information except image is being saved on server using Javascript, Json

相关标签:
7条回答
  • 2020-12-05 06:22

    There are two ways to post files (images) asynchronously If your target browsers support file api, you can use the following: HTML:

    <input type="file" name="etlfileToUpload" id="etlfileToUpload"  />
    

    JavaScript

    // Call this function on upload button click after user has selected the file 
    function UploadFile() {
        var file = document.getElementById('etlfileToUpload').files[0];
        var fileName = file.name;    
        var fd = new FormData();    
        fd.append("fileData", file);    
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
        xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
        xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
        xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
        xhr.open("POST", "{URL}", true); 
        xhr.send(fd);
    }
    
    
    function UploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            $("#uploading").text(percentComplete + "% ");        
        }
    }
    
    function UploadComplete(evt) {
        if (evt.target.status == 200)
            alert(evt.target.responseText);
        else {
            alert("Error Uploading File");
        }
    }
    
    function UploadFailed(evt) {    
        alert("There was an error attempting to upload the file.");
    }
    
    function UploadCanceled(evt) {    
        alert("The upload has been canceled by the user or the browser dropped the connection.");
    }
    

    or you can use swf tools like uploadify

    0 讨论(0)
  • 2020-12-05 06:27
    $(document).ready(function(){
       var status = $('#status');
    
            $('#frmUpload').ajaxForm({
                beforeSend: function () {
                    if ($("#file").val() != "") {                   
                        $("#progressDiv").show();                    
                    }
                    status.empty();
                },
                success: function () {
                    showTemplateManager();
                },
                complete: function (xhr) {
                    if ($("#file").val() != "") {
                        var millisecondsToWait = 500;
                        setTimeout(function () {                       
                         $("#progressDiv").hide();
                        }, millisecondsToWait);
                    }
                    status.html(xhr.responseText);
                }
            });
    });
    
    0 讨论(0)
  • 2020-12-05 06:29

    I also got similar Problem and after getting stuck up for many days finally this link helped me

    Jquery Uploadiy with Progress Bar to be Used with MVC

    and this is how i managed it

    public JsonResult Upload(HttpPostedFileBase file)
    {
        if (Session["myAL"] == null)
        {
            al = new ArrayList();
        }
        else
            al = (ArrayList)Session["myAL"];
    
        var uploadFile = file;
    
            if (uploadFile != null && uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Uploads"),
                                                   Path.GetFileName(uploadFile.FileName));                    
                al.Add(filePath);
                Session["myAL"] = al;
                uploadFile.SaveAs(filePath);
            }
    
        var percentage = default(float);
    
        if (_totalCount > 0)
        {
            _uploadCount += 1;
            percentage = (_uploadCount / _totalCount) * 100;
        }
    
        return Json(new
        {
            Percentage = percentage
        });
    }
    

    How to Implement Attach More Files in MVC and jquery for FileUploading

    0 讨论(0)
  • 2020-12-05 06:30

    I personally don't prefer to use any kind of third party tool other than java script, css or html. I will go with first approach shown by UmairP. But if you want to spare your self for writting to much of a code. Here is a nice plugin of jquery.

    And also there is a demo for asp.net mvc with this plugin.

    Please have a look. Let me know if any further information needed.

    0 讨论(0)
  • 2020-12-05 06:30

    Try this its working for me

       <input type="file" name="Upload" id="Upload" />
    
    $('#Upload').change(function () {
        debugger;
        var file = document.getElementById('Upload').files[0];
        var fileName = file.name;
        var fd = new FormData();
        fd.append("fileData", file);
        fd.append("key", '@Model.Id');
    
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
        xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
        xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
        xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
        xhr.open("POST", "/ImageHandler.ashx", true);
        xhr.send(fd);
    });
    
    
    function UploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            //$("#uploading").text(percentComplete + "% ");
        }
    }
    
    function UploadComplete(evt) {
        //if (evt.target.status == 200)
            //alert(evt.target.responseText);
        //else {
        //   // alert("Error Uploading File");
        //}
    }
    
    function UploadFailed(evt) {
       // alert("There was an error attempting to upload the file.");
    }
    
    function UploadCanceled(evt) {
        //alert("The upload has been canceled by the user or the browser dropped the connection.");
    }
    

    Handler:

    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");]
    
    
    
            string filePath = Constants.ImageFolderPath;
    
            //write your handler implementation here.
            if (context.Request.Files.Count <= 0)
            {
                context.Response.Write("No file uploaded");
            }
            else
            {
                for (int i = 0; i < context.Request.Files.Count; ++i)
                {
                    HttpPostedFile file = context.Request.Files[i];
                    if (context.Request.Form != null)
                    {
                        string imageid = context.Request.Form.ToString();
                        imageid = imageid.Substring(imageid.IndexOf('=') + 1);
    
                        if (file != null)
                        {
                            string ext = file.FileName.Substring(file.FileName.IndexOf('.'));
                            if (ext.ToLower().Contains("gif") || ext.ToLower().Contains("jpg") || ext.ToLower().Contains("jpeg") || ext.ToLower().Contains("png"))
                            {
    
                                byte[] data;
                                using (Stream inputStream = file.InputStream)
                                {
                                    MemoryStream memoryStream = inputStream as MemoryStream;
                                    if (memoryStream == null)
                                    {
                                        memoryStream = new MemoryStream();
                                        inputStream.CopyTo(memoryStream);
                                    }
                                    data = memoryStream.ToArray();
                                    File.WriteAllBytes(Constants.ImageFolderPath + imageid + ".jpg", (byte[])data);
                                    //club.club_image = Convert.ToBase64String(data);
                                }
                            }
                        }
                    }
                    else
                    {
    
                    }
    
                    //file.SaveAs(context.Server.MapPath(filePath + file.FileName));
                    context.Response.Write("File uploaded");
                }
            }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 06:34
    <input type="file" name="file" id="file" style="width: 100%;"onchange="readURL(this);" />
    
     if (file != null && file.ContentLength > 0)
                    {
                        string filename = Path.GetFileName(file.FileName);
                        string imgpath = Path.Combine(Server.MapPath("~/Img/"), filename);
                        file.SaveAs(imgpath);
                        student.photo = imgpath;
                    }
    
    function readURL(input)
        {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
    
                reader.onload = function (e) {
                    $('#imgUser')
                        .attr('src', e.target.result)
                        .width(150)
                        .height(200);
                };
    
                reader.readAsDataURL(input.files[0]);
            }
        }
    
    0 讨论(0)
提交回复
热议问题