MVC File Upload-asynchronous upload with jquery and client authentication type and size

Source: Internet
Author: User
Tags jquery file upload

This article experiences MVC uploading files, transitioning from form uploads to jquery asynchronous uploads.

MVC's most basic upload file is through form form submission method

-Foreground View Section

Using (Html.BeginForm ("Multipart/form-data"}) {)%>
    <input name ="UploadFile" type="file"/> 
    <input type=value="Upload File"/> 
<%}%>

-Controller Section

[Httpmethod.post]
Public ActionResult FileUpload (HttpPostedFileBase uploadfile)
{
    if (Uploadfile.contenctlength > 0)
    {
        Get Save Path
        String filePath = Path.Combine (HttpContext.Server.MapPath (
                        Path.getfilename (Uploadfile.filename));
        Uploadfile.saveas (FilePath);
    }
    return View ();
}

But the entire page will refresh, in the face of a single, simple requirements, there is value. But in a real project, of course, you want to do it asynchronously.

Using jquery file Upload plugin for asynchronous uploads

-Ideas

1, using the jquery file Upload plugin fileupload () method, for type= "file" input set Url,datatype, and give the data to a global variable var jqxhrdata.
2, click the Upload button, submit data Jqxhrdata.submit ()
3, the Controller method is responsible for uploading files to the specified folder

-js file that needs to be referenced

    <script src="~/scripts/jquery-1.9.1.min.js" ></script>
    <script src="~/scripts/jquery-ui-1.9.2.min.js" ></script>
    <script src="~/scripts/jquery.fileupload.js" ></script>
    <script src="~/scripts/jquery.fileupload-ui.js" ></script>
    <script src="~/scripts/jquery.iframe-transport.js" ></script>

-view Model

The property type is HttpPostedFileBase.

Using System.Web;
Namespace Mvcapplication1.models
{
    Class MyModel
    {
        Public HttpPostedFileBase MyFile {get; set;}
    }
}    

-homecontroller

Using SYSTEM.WEB.MVC;
Namespace Mvcapplication1.controllers
{
    Class Homecontroller:controller
    {
        Public ActionResult Index ()
        {
            return View ();
        }
    }
}

-home/index.cshtml

@model MvcApplication1.Models.MyModel
@{
    "Index";
    "~/views/shared/_layout.cshtml";
}
<div>
    New {id="simple", type="file"}) <br/> 
    <a href="#" id="Simpleupload" > Start simple upload </a> 
</div>
<div>
    <input type="file" name="MyFile" id="check"/> <br/>  
    <a href="#" id="Checkupload" > Start checking and uploading </a> 
</div>
@section scripts
{
    <script src="~/scripts/jquery-1.9.1.min.js" ></script>
    <script src="~/scripts/jquery-ui-1.9.2.min.js" ></script>
    <script src="~/scripts/jquery.fileupload.js" ></script>
    <script src="~/scripts/jquery.fileupload-ui.js" ></script>
    <script src="~/scripts/jquery.iframe-transport.js" ></script>
    <script type="Text/javascript" >
        var jqxhrdata;
        $ (function () {
            Initsimplefileupload ();
            Initfileuploadwithcheck ();
            Simple upload
            $ (' #simpleupload '). On (' click ', Function () { 
                if (jqxhrdata) {
                    Jqxhrdata.submit ();
                }
                False
            });
            Check the picture file type and size
            $ (' #checkupload '). On (' click ', Function () { 
                if (jqxhrdata) {
                    True
                    var uploadfile = jqxhrdata.files[0];
                    if (! ( /\. (gif|jpg|jpeg|tiff|png) $/i). Test (Uploadfile.name)) {
                        Alert (' Allow image format Gif|jpg|jpeg|tiff|png ');
                        False
                    4mb
                        Alert (' picture size cannot be greater than 4 MB ');
                        False
                    }
                    if (isstartupload) {
                        Jqxhrdata.submit ();
                    }
                }
                False
            });
        });
        Simple upload
        function Initsimplefileupload () {
            $ (' #simple '). FileUpload ({
                ' @Url. Action ("UploadFile", "File") ',
                ' JSON ',
                Add:function (E, data) {
                    Jqxhrdata = data;
                },
                Done:function (event, data) {
                    if (data.result.isUploaded) {
                        alert (data.result.message);
                    else {
                        alert (data.result.message);
                    }
                },
                Fail:function (event, data) {
                    if (data.files[0].error) {
                        alert (data.files[0].error);
                    }
                }
            });
        }
        Check the picture file type and size
        function Initfileuploadwithcheck () {
            $ (' #check '). FileUpload ({
                ' @Url. Action ("UploadFile", "File") ',
                ' JSON ',
                Add:function (E, data) {
                    Jqxhrdata = data;
                },
                Done:function (event, data) {
                    if (data.result.isUploaded) {
                        alert (data.result.message);
                    else {
                        alert (data.result.message);
                    }
                },
                Fail:function (event, data) {
                    if (data.files[0].error) {
                        alert (data.files[0].error);
                    }
                }
            });
        }
    </script>
}

Corresponding interface:

-filecontroller

Using System.IO;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Namespace Mvcapplication1.controllers
{
    Class Filecontroller:controller
    {
        Public ActionResult Index ()
        {
            return View ();
        }
        [HttpPost]
        Public ActionResult UploadFile ()
        {
            HttpPostedFileBase myFile = request.files["MyFile"];
            False
            "Upload failed";
            Null && Myfile.contentlength! = 0)
            {
                String pathforsaving = Server.MapPath ("~/uploads");
                if (this. Createfolderifneeded (pathforsaving))
                {
                    Try
                    {
                        Myfile.saveas (Path.Combine (pathforsaving, myfile.filename));
                        True
                        "Upload success";
                    }
                    catch (Exception ex)
                    {
                        String. Format ("Upload file failed: {0}", ex.) Message);
                    }
                }              
            }
            Return Json (new {isuploaded = isuploaded, message = message});
        }
        <summary>
        Check if you want to create an upload folder
        </summary>
        <param name= "path" > Path </param>
        <returns></returns>
        BOOL Createfolderifneeded (string path)
        {
            True
            if (! Directory.Exists (PATH))
            {
                Try
                {
                    Directory.CreateDirectory (path);
                }
                catch (Exception)
                {
                    TODO: Handling Exceptions
                    False
                }
            }
            return result;
        }
    }
}

-Also, you need to set the maximum allowable file size in the configuration file

  <system.web>
    <!--10240 Kb = ten mb-->
    "10240"/>
    ...
  </system.web>

-Results

After uploading successfully, more uploads folder:

Upload PDF format, error:

MVC File Upload-asynchronous upload with jquery and client authentication type and size

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.