Asp.net mvc implements the idea and method of bringing progress bars to file uploads, asp. netmvc

Source: Internet
Author: User

Asp.net mvc implements the idea and method of bringing progress bars to file uploads, asp. netmvc

Preface

File upload and download operations are often important in actual projects. NET Web Form, we can use a lot of server controls, FileIpload is one of them, but in ASP. NET is not recommended to use those server controls, because it violates the three-tier architecture principles. I recently learned how to upload files using ASP. NET MVC by referring to network documents. This article focuses on the implementation of asp.net mvc with a progress bar. Let's take a look at it.

Implementation

Ajax uploads files asynchronously and starts polling when uploading files to obtain the File Upload progress in real time. I used the memcached cache to save the progress. Because the project is used elsewhere, I used it directly. Note: you cannot use the session to save the progress because the session is thread-safe and cannot get the progress in real time. However, try httpcache or memorycache. I have not tried the two. Please try it on your own.

Ps: Websocket is also good, but I have never tried it. You can try it.

Below:

The implementation method is as follows:

I used two jq plug-ins to upload files through front-end ajax. One is ajaxfileupload and the other is jquery. form. js (if you need to download it, please Baidu ). For more usage of jQuery plug-ins, refer to related topics on this site: jQuery common plug-ins and usage summary.

The following code is ajaxFileUpload:

$. AjaxFileUpload ({url: '/WxManage/Media/uploadimag', // secureuri: false, // whether the security protocol is required, generally set to false fileElementId: 'postfile', // The ID type of the file upload field: "post", dataType: 'json', // the return value type is generally set to json success: function (data, status) // server success response handler {CloseProgressbar (); // close the progress bar and set the progress bar to 100 if (data. status = 1) {layer. msg (data. msg, {icon: 1, time: 1000}, function () {parent. location. reload () ;}) ;}else {$ ("# btnUploadFile "). attr ("disabled", false); layer. msg (data. msg, {icon: 2, time: 1000}) ;}, error: function (data, status, e) // server response failure handler {$ ("# btnUploadFile "). attr ("disabled", false); CloseProgressbar (); layer. closeAll ("dialog"); layer. msg ("Upload Failed", {icon: 2, time: 1000 });}});

The action that the backend receives the file upload request:

[HttpPost] public ActionResult UploadImage (HttpPostedFileBase postFile) {if (postFile = null) {return Json (BasicConfig. messageConfig. fail ("file to be uploaded cannot be blank");} try {string format = postFile. fileName. split ('. '). last (); // suffix SaveFile (postFile); return Json (BasicConfig. messageConfig. success ("uploaded successfully");} catch (Exception ex) {return Json (BasicConfig. messageConfig. fail ("Upload Failed "));}}

The SaveFile method is used to save files. The file stream method is used to save files so as to calculate the upload progress:

Core code:

FileStream fs = new FileStream (fileSavePath, FileMode. create); BinaryWriter bw = new BinaryWriter (fs); BinaryReader br = new BinaryReader (postFile [I]. inputStream); int readCount = 0; // number of bytes read at a time while (readCount = br. read (bufferByte, 0, readBufferSize)> 0) {bw. write (bufferByte, 0, readCount); // Write bytes to the file stream bw. flush (); saveCount + = readCount; // mem of the uploaded progress. setValue ("Admin_UploadSpeed _" + Session. sessionID, (saveCount * 1.0/totalCount ). toString ("0.00"), 60); // update to the memcached cache Thread. sleep (200); // deliberately paused to see the obvious process}

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

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.