ASP. NET MVC implementation upload file with progress bar

Source: Internet
Author: User

Idea: Ajax uploads files Asynchronously and starts polling when uploading files to get the file upload progress in real time. Save Progress I'm using the memcached cache because it's used elsewhere in the project, so I'll use it directly. Note: You cannot use session to save progress because the session is thread-safe and cannot get the progress in real time, but try HttpCache or memorycache, these two I have not tried, please try it yourself.

PS: Using WebSocket to achieve is also good, but I have not tried, the heart of the great God can go to try.

Here's a photo:

Front-end Ajax uploading files, I used two JQ plugins. One is Ajaxfileupload, one is jquery.form.js (if need to download, please Baidu)

The following code is ajaxfileupload :

$.ajaxfileupload ({URL:'/wxmanage/media/uploadimage',//server-side request address for file uploadsSecureuri:false,//whether a security protocol is required, generally set to falseFileelementid:'Postfile',//ID of the file upload domainType"Post", DataType:'JSON',//The return value type is generally set to JSONSuccess:function (data, status)//Server Success Response handler function{Closeprogressbar ();//Close progress bar set progress bar progress to                if(Data.status = =1{layer.msg (data.msg, {icon:1, Time: +},function () {parent.location.reload ();                }); } Else {                    $("#btnUploadFile"). attr ("Disabled",false); Layer.msg (data.msg, {icon:2, Time: + }); }}, Error:function (data, status, E)//Server Response Failure handler function            {                $("#btnUploadFile"). attr ("Disabled",false);                Closeprogressbar (); Layer.closeall ("Dialog"); Layer.msg ("Upload failed", {icon:2, Time: + }); }        }    );

The back end receives the file upload request action:

1 [HttpPost]2          Publicactionresult uploadimage (httppostedfilebase postfile)3         {4             if(Postfile = =NULL)5             {6                 returnJson (BasicConfig.MessageConfig.Fail ("the upload file must not be empty"));7             }8 9             TryTen             { One                 stringFormat = PostFile.FileName.Split ('.'). Last ();//suffix name A SaveFile (postfile); -                 returnJson (BasicConfig.MessageConfig.Success ("Upload Successful")); -             } the             Catch(Exception ex) -             { -                 returnJson (BasicConfig.MessageConfig.Fail ("Upload failed")); -             } +}

The SaveFile method is the method of saving the file, which is saved by the file stream to facilitate the calculation of the upload progress:
Core code:
1FileStream fs =NewFileStream (Filesavepath, filemode.create);2BinaryWriter bw =NewBinaryWriter (FS);3BinaryReader br =NewBinaryReader (Postfile[i]. InputStream);4                 5                 intReadcount =0;//number of bytes read in a single time6                  while((Readcount = br.) Read (Bufferbyte,0, readbuffersize)) >0)7                 {8Bw. Write (Bufferbyte,0, Readcount);//Write bytes to file stream9 bw. Flush ();TenSavecount + = Readcount;//progress that has been uploaded OneMem. SetValue ("Admin_uploadspeed_"+ Session.SessionID, (Savecount *1.0/TotalCount). ToString ("0.00"), -);//will be updated into the memcached cache AThread.Sleep ( $);//in order to see the obvious process deliberately suspended -}

ASP. NET MVC implementation upload file with progress bar

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.