MVC file picture Ajax upload Lightweight solution using Client Jsajaxfileuploader plugin 02-Multiple file Upload

Source: Internet
Author: User

In the previous article, the use of the client-side Jjsajaxfileuploader plug-in implementation of single-file asynchronous upload, this article implementation of multi-file asynchronous upload.

This article source in GitHub , first look at the effect:

The upload file shows the progress bar.
Stop the upload button and close the thumbnail button.
Restricts the type of upload file.
Limit the size of uploaded files.
When uploading multiple files successfully, the thumbnail image and file name are displayed:

Click the Delete button on the interface, delete the interface, delete the files in the folder synchronously.
Then click Upload file, the interface appends a new line of thumbnails, file name, delete button:

-homecontroller

Change the uploaded file name to a GUID-named format, avoid multiple file name duplication, save to a folder, and pass the callback information to the view in JSON form. For deletion, you need to receive the file name parameter from the view.

        #region uploading multiple files
         Public ActionResult Showmultiple ()
        {
            return View ();
        }
        [HttpPost]
         Public ActionResult Uplpadmultiplefiles ()
        {
            New List<uploadfileresult> ();
            foreach (string in Request.Files)
            {
                 as HttpPostedFileBase;
                if null)
                {
                    continue;
                }
                var fileName = DateTime.Now.ToString ("YYYYMMDDHHMMSS") +
                               HPF. Filename.substring (HPF. Filename.lastindexof ('. '));
                var fileName = Guid.NewGuid (). ToString () +
                               Hpf. Filename.substring (HPF. Filename.lastindexof ('. '));
                string pathforsaving = Server.MapPath ("~/ajaxupload");
                if (this.) Createfolderifneeded (pathforsaving))
                {
                    Hpf. SaveAs (Path.Combine (pathforsaving, fileName));
                    Results. ADD (new Uploadfileresult ()
                    {
                        FilePath = Url.content (String.Format ("~/ajaxupload/{0}", FileName),
                        filename = filename,
                        true,
                        Length = HPF. ContentLength,
                        "Upload succeeded",
                        Type = HPF. ContentType
                    });
                }
            }
            return Json (new
            {
                Name = Results[0]. FileName,
                Type = Results[0]. Type,
                string. Format ("{0} bytes", Results[0]. Length),
                Path = Results[0]. FilePath,
                msg = Results[0]. Message
            });
        }
        #endregion
        #region Common method
        <summary>
        Check if you want to create an upload folder, and if not, create
        </summary>
        <param name= "path" > Path </param>
        <returns></returns>
        Private BOOL createfolderifneeded (string path)
        {
            BOOL true;
            if (! Directory.Exists (PATH))
            {
                Try
                {
                    Directory.CreateDirectory (path);
                }
                Catch (Exception)
                {
                    TODO: Handling Exceptions
                    false;
                }
            }
            return result;
        }
        Delete files based on file name
        [HttpPost]
         Public ActionResult deletefilebyname (string name)
        {
            string pathforsaving = Server.MapPath ("~/ajaxupload");
            System.IO.File.Delete (Path.Combine (pathforsaving, name));
            return Json (new
            {
                True
            });
        }
        #endregion

-home/showmultiple.cshml

The foreground view mainly does the following several things:
Upload successfully dynamically create table rows display thumbnails, file names, and delete buttons
Click the Delete button to implement the interface to delete and delete files in the folder
Because table rows are dynamically generated, you need to register the event "bubbling" with the Delete button: $ (' #tb '). On ("click", ". Delimg", function ()

    <meta name="viewport" content="Width=device-width" />
    <title>Index</title>
    <link href="~/content/jsajaxfileuploader/jquery.jsajaxfileuploader.css" rel="stylesheet" />
    <script src="~/scripts/jquery-1.10.2.js"></script>
    <script src="~/scripts/jsajaxfileuploader/jquery.jsajaxfileuploadermultiple.js"></script>
    <style type="Text/css">
        #tb table{
            Border-collapse:collapse;              
            width:600px;         
        }
        #tb TD {
            Text-align:center;
            padding-top:5px;
            width:25%;
        }
        #tb TR {
            Background-color: #E3E3E3;
            line-height:35px;
        }
        . showimg {
            width:50px;
            height:50px;
        }
    </style>
    <script type="Text/javascript">
        $ (function () {
            Hide a table showing pictures
            $ (' #tbl '). Hide ();
            $ (' #testId '). Jsajaxfileuploader ({
                ' @Url. Action ("Uplpadmultiplefiles", "Home") ',
                ' Select multiple upload files ',
                ' photo ',
                maxfilesize:512000,    //max kb file 1kb=1024 bytes
                ' Gif|jpg|jpeg|png ',
                false,
                Zoomwidth:360,
                Zoomheight:360,
                Success:function (data) {
                    $ (' #tbl '). Show ();
                    Createtabletr (Data.path, data.name);
                },
                Error:function (data) {
                    Alert ("Error ~ ~ ~");
                }
            });
            Click the Delete link on the line
            $ (' #tb '). On ("click"". Delimg", function () {
                var $link = $ (this);
                $.ajax ({
                    false,
                    ' @Url. Action ("Deletefilebyname", "Home") ',
                    "POST",
                    Data: {name: $link. Parent (). Prev (). Find ('. Imgname '). Text ()},
                    Success:function (data) {
                        if (data.msg) {
                            Alert ("Image deletion succeeded");
                            $link. Parent (). Parent (). remove ();
                        }
                    },
                    Error:function (JQXHR, Textstatus, Errorthrown) {
                        Alert ("Error" ""' (Status: '"', Error: '" ') ");
                    }
                });
            });
        });
        Create a table
        function Createtabletr (img, imgname) {
            var table = $ (' #tbl ');
            Table.append ("<tr><td><img class= ' showimg ' src= '""'/></td><td colspan= ' 2 ' ><span class= ' imgname ' > "" </span></td><td><a class= ' delimg ' href= ' Javascript:void (0) ' > Delete </a></td></tr> ');
        }
    </script>
<body>
    <div id="TestID"></div>
    
    <div id="TB">
        <table id="TBL">
            <tbody>              
            </tbody>
        </table>
    </div>
</body>

In addition:
The multiple property of the input element in the source JS file needs to be restored so that it can receive multiple files.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.