Ajaxfileupload Plugin upload image function, use MVC and aspx to do the background each write a case

Source: Internet
Author: User
Tags save file

HTML code and JS code

@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title> <script src="~/js/jquery-1.8.3.min.js"></script> <script src="~/js/ajaxfileupload.js"></script> <script type="Text/javascript">$ (function () {$ ("#butLoad"). Click (function () {$ ("#img1"). attr ("src",".. /images/timg.gif"); //Invoke Action$.ajaxfileupload ({URL:".. /upload/upload", Secureuri:false,//generally set to falseFileelementid:'Img',//file upload Space id attribute <input type= "file" id= "Img" name= "file"/>DataType:'JSON',//return value typeSuccess:function (data, status)//Server Success Response handler function                    {                        $("#img1"). attr ("src", Data.imgurl); if(typeof(data.error)! ='undefined') {                            if(Data.error! ="') {alert (data.error); } Else{alert (data.msg); }}, Error:function (data, status, E)//Server Response Failure handler function{alert (e);            }                });            }); $("#butLoadAsp"). Click (function () {$ ("#imgAsp"). attr ("src",".. /images/timg.gif"); //Call aspx$.ajaxfileupload ({URL:".. /ajax/upload.aspx?__action=uploadimg", Secureuri:false,//generally set to falseFileelementid:'imgasp',//file upload Space id attribute <input type= "file" id= "Img" name= "file"/>DataType:'JSON',//return value typeSuccess:function (data, status)//Server Success Response handler function                    {                        $("#imgAsp"). attr ("src", Data.imgurl); if(typeof(data.error)! ='undefined') {                            if(Data.error! ="') {alert (data.error); } Else{alert (data.msg); }}, Error:function (data, status, E)//Server Response Failure handler function{alert (e);            }                });        });        }); function Chimages (obj) {$ ("#img1"). attr ("src", Obj.value)} </script>"file"Id="Img"Name="file"Onchange="Chimages (This)"/> @* Note: Name must be written *@        <button id="Butload"> Uploads </button> ""Id="IMG1"alt="Please select a picture"Width=" $"/> </div> <div> "file"Id="imgasp"Name="file"/> @* Note: Name must be written *@        <button id="butloadasp"> Uploads </button> ""Id="imgasp"alt="Please select a picture"Width=" $"/> </div></body>



Code in MVC Control

[HttpPost]//Filter         PublicJsonresult UpLoad () {httpfilecollectionbase files= Request.Files;//This can only be done with <input type= "file"/>, because the server control is a httpinputfile type            Objectresult =New{error="Error", msg="Upload failed", Imgurl= files[0].            FileName}; stringmsg =string.            Empty; stringError =string.            Empty; stringImgurl; if(Files. Count >0)            {                stringSavepath = Server.MapPath ("/") +"uploadimg\\";//Save File Address//string savedir = System.Web.HttpContext.Current.Server.MapPath (Savepath);                if(!directory.exists (Savepath))                {directory.createdirectory (Savepath); } files[0]. SaveAs (Savepath + System.IO.Path.GetFileName (files[0].                FileName)); Msg="Success! File size is:"+ files[0].                ContentLength; Imgurl=".. /uploadimg/"+ files[0].                FileName; Result=New{error="Success", msg= msg, imgurl=Imgurl}; }            returnJson (Result,"text/html"); }


Aspx.cs Code

 Public Partial classUpLoad:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) {            stringAction = request["__action"]; if(action==NULL|| Action = =string. Empty)return; Page P= This; Type PageType=P.gettype (); MethodInfo Method=Pagetype.getmethod (action); if(Method! =NULL) method. Invoke (P,NULL); }         Public voiduploadimg () {httpfilecollection files= Request.Files;//This can only be done with <input type= "file"/>, because the server control is a httpinputfile type//Object result = new {error = "error", msg = "Upload Failed", Imgurl = Files[0]. FileName};            stringresult ="{error: ' Error ', msg: ' Upload failed ', Imgurl: '"+ files[0]. FileName +"'}"; stringmsg =string.            Empty; stringError =string.            Empty; stringImgurl; if(Files. Count >0)            {                stringSavepath = Server.MapPath ("/") +"uploadimg\\";//Save File Address//string savedir = System.Web.HttpContext.Current.Server.MapPath (Savepath);                if(!directory.exists (Savepath))                {directory.createdirectory (Savepath); } files[0]. SaveAs (Savepath + System.IO.Path.GetFileName (files[0].                FileName)); Msg="Success! File size is:"+ files[0].                ContentLength; Imgurl=".. /uploadimg/"+ files[0].                FileName; Result="{error: '"+ Error +"', msg: '"+ msg +"', Imgurl: '"+ Imgurl +"'}";            } response.clear (); Response.Write (Result.            ToString ());        Response.End (); }    } 

MVC and aspx are somewhat different, MVC gets httpinputfile with Httpfilecollectionbase class, aspx gets httpinputfile with Httpfilecollection class

Personal study, please give me a lot of advice

Code: Http://files.cnblogs.com/files/BensonHai/UploadImage.rar I wrote it with VS2015.

Ajaxfileupload Plugin upload image function, use MVC and aspx to do the background each write a case

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.