MVC file picture Ajax upload Lightweight solution using client Jsajaxfileuploader Plugin 01-Single File Upload

Source: Internet
Author: User

Some time ago to do a few pictures, file upload demo, using the client Query-file-upload plug-in and server-side badkload components for multi-file asynchronous upload, such as " MVC File Upload 04-use client Jquery-file-upload plug-in and server-side backload components to achieve multi-file asynchronous upload ", in terms of demo, the effect is good, but to the actual project, Find it difficult to integrate with projects using Query-file-upload plug-in and server-side badkload components, with a "heavy" feel. In contrast, jsajaxfileuploader this plug-in is more "lightweight", it can help us to achieve the asynchronous upload and management of a single file or multiple files, and has a good client effect, its demo here.

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

Upload file display progress bar:

Stop the upload button and close the thumbnail button:

Limit the types of uploaded files:

Limit the size of uploaded files:

Display thumbnails, filenames, and callback information after successful uploads:

Click the Delete button on the interface, delete the interface, delete the files in the folder synchronously.
Re-upload files, interface Delete, delete files in the folder synchronously, and the interface displays new thumbnails, filenames and so on.

-homecontroller

Due to the need to save to the folder file path, file name and so on back to the interface, so need a class, specifically responsible for back to the client required information.

     Public class Uploadfileresult
    {
         Public string FileName {get; set;}
         Public int Length {get; set;}
         Public string Type {get; set;}
         Public BOOL IsValid {get; set;}
         Public string Message {get; set;}
         Public string
    }

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

        #region Upload a single file
        Show
         Public ActionResult Index ()
        {
            return View ();
        }
        Receive uploads
        [HttpPost]
         Public ActionResult UploadFile ()
        {
            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 ('. '));
                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
            });
        }    
        #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/index.cshml

The foreground view mainly does the following several things:
Check the table for data before each upload, and if so, implement the interface to delete and synchronize files in the folder
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.jsajaxfileuploadersingle.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 ("UploadFile", "Home") ',
                ' Choose Upload file ',
                FileName: ' Photo ',
                maxfilesize:512,    //max kb file 1kb=1024 bytes
                ' Gif|jpg|jpeg|png ',
                false,
                Zoomwidth:360,
                Zoomheight:360,
                Beforesend:function (file) {
                    if ($ ('. Imgname '"") {
                        Deleteimg ();
                        $ (' #tbl '). Hide ();
                    }
                },
                Success:function (data) {
                    $ ('. file_name '). html (data.name);
                    $ ('. File_type '). html (data.type);
                    $ ('. File_size '). html (data.size);
                    $ ('. File_path '). html (Data.path);
                    $ ('. file_msg '). html (DATA.MSG);
                    Createtabletr ();
                    $ (' #tbl '). Show ();
                    $ ('. showimg '). attr ("src", Data.path);
                    $ ('. Imgname '). Text (data.name);
                },
                Error:function (data) {
                    alert (data.msg);
                }
            });
            Click the Delete link to delete the image you just uploaded
            $ (' #tbl '). On ("click"". Delimg", function () {
                Deleteimg ();
                Window.location.reload ();
            });
        });
        Delete Image method: Click the delete link or upload a new image to delete the original image to use
        function deleteimg () {
            $.ajax ({
                false,
                ' @Url. Action ("Deletefilebyname", "Home") ',
                "POST",
                Data: {Name: $ ('. Imgname '). Text ()},
                Success:function (data) {
                    if (data.msg) {
                        Alert ("Image deletion succeeded");
                        $ ('. delimg '). Parent (). Parent (). remove ();
                        
                    }
                },
                Error:function (JQXHR, Textstatus, Errorthrown) {
                    Alert ("Error" ""' (Status: '"', Error: '" ') ");
                }
            });
        }
        Create a table
        function Createtabletr () {
            var table = $ (' #tbl ');
            Table.append ("<tr><td></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>
        class="file_name"></div>
        <br/>
        class="File_type"></div>
        <br/>
        class="File_size"></div>
        <br/>
        class="File_path"></div>
        <br/>
        class="File_msg"></div>
</body>

In addition:
The multiple attribute of the INPUT element in the source JS file needs to be deleted so that it can only receive individual 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.