Use File Upload in ASP. net mvc, asp. netmvc

Source: Internet
Author: User

Use File Upload in ASP. net mvc, asp. netmvc

Article Reprinted from: http://www.cnblogs.com/jiekzou/

Here, I use the uploadify component to implement the asynchronous Multifile upload function without refreshing new files.

1. First download the component package uploadify. the version I use here is 3.1.

2. Download and decompress the package. Copy the package to the MVC project.

 

3. Add the new folder Uploads under the root directory, and then create the Controller UploadifyController. cs

Using System; using System. collections. generic; using System. IO; using System. linq; using System. web; using System. web. mvc; namespace Shop. controllers {public class UploadifyController: Controller {// GET:/Uploadify/public ActionResult Index () {return View ();} [AcceptVerbs (HttpVerbs. post)] public JsonResult Upload (HttpPostedFileBase fileData) {if (fileData! = Null) {try {// File Upload path string filePath = Server. MapPath ("~ /Uploads/"); if (! Directory. exists (filePath) {Directory. createDirectory (filePath);} string fileName = Path. getFileName (fileData. fileName); // the name of the original file string fileExtension = Path. getExtension (fileName); // file extension string saveName = Guid. newGuid (). toString () + fileExtension; // save the file name fileData. saveAs (filePath + saveName); return Json (new {Success = true, FileName = fileName, SaveName = saveName});} catch (Exception Ex) {return Json (new {Success = false, Message = ex. message}, JsonRequestBehavior. allowGet) ;}} else {return Json (new {Success = false, Message = "select the file to upload! "}, JsonRequestBehavior. AllowGet );}}}}

4. Add an Index View

@ {ViewBag. Title = "Index"; Layout = null ;}< link href = "~ /Content/uploadify/uploadify.css "rel =" stylesheet "/> <script src = "~ /Scripts/jquery-1.7.1.min.js "> </script> <script src = "~ /Content/uploadify/jquery. uploadify-3.1.min.js "> </script> <script type =" text/javascript "> $ (function () {$ (" # file_upload "). uploadify ({// specify the swf file 'swf ':' @ Url. content ("~ /Content/uploadify/uploadify.swf ") ', // backend processing page 'upload':'/Uploadify/upload', // The text displayed by the button 'buttontext ': 'upload image', // The display height and width. The default height is 30; width 120 // 'height': 15, // 'width': 80, // The default object type is 'all files' for All objects ';'*. * '// The text 'filetypedesc': 'image files' displayed in the file type drop-down menu at the bottom of the browser window. // The file suffix 'filetypeexists ':'*. gif ;*. jpg ;*. png ', // other parameters sent to the background are specified using formData // 'formdata': {'somekey': 'somevalue', 'someotherkey': 1 }, // id of the element you want to use as a file queue on the Upload File page. The default value is false, which is automatically generated without # // 'queueid': 'filequeue ', // select a file and automatically upload 'auto': false, // if it is set to true, multiple files are allowed to be uploaded 'multi': true });}); </script> <div> @ * used as the file queue area * @ <div id = "fileQueue"> </div> <input type = "file" id = "file_upload" name = "file_upload"/> <p>
<A href = "javascript: $ ('# file_upload'). uploadify ('upload');"> upload the first file </a>
<A href = "javascript: $ ('# file_upload'). uploadify ('upload', '*');"> upload queue </a>
<A href = "javascript: $ ('# file_upload'). uploadify ('cancel');"> cancel the first one </a>
<A href = "javascript: $ ('# file_upload'). uploadify ('cancel', '*');"> cancel a queue </a>
</P> </div>

5. Start the program to view the effect

 

Uploadify Common attribute settings

AUto: Specifies whether to automatically upload a file after the file is selected. The default value is true.

ButtonText: Set the upload button to display text.

ButtonImage: Set the upload button background image.

Multi: Whether to allow multiple files to be uploaded at a time. The default value is true.

FileTypeDesc: Specifies the description of the format of the image to be uploaded;

FileTypeExts: sets the format of images that can be uploaded.

RemoveCompleted: Sets whether to remove uploaded files from the queue. The default value is true.

QueueSizeLimit: Sets the number of files allowed to be uploaded in the upload queue. The default value is 999.

UploadLimit: Sets the number of files that can be uploaded. The default value is 999.

Uploadify common event settings

OnUploadComplete: An event is triggered when a single file is uploaded.

$ (Function () {$ ("# file_upload"). uploadify ({
'Swf ':' @ Url. Content ("~ /Content/uploadify/uploadify.swf ") ', // specify the swf File
'Upload': '/Uploadify/upload', // backend processing page 'onuploadcomplete': function (file) {alert ('the file' + file. name + 'finished processing. ');}});});

OnQueueComplete: Triggered when all files in the queue are uploaded.

$(function() {    $("#file_upload").uploadify({        'swf'      : '@Url.Content("~/Content/uploadify/uploadify.swf")',        'uploader' : 'uploader': '/Uploadify/Upload',        'onQueueComplete' : function(queueData) {            alert(queueData.uploadsSuccessful + ' files were successfully uploaded.');        }    });}); 

OnUploadSuccess: Triggers an event after a single file is uploaded successfully.

$ (Function () {$ ('# file_upload'). uploadify ({'buttonimage': '@ Url. Content ("~ /Content/uploadify/browse-btn.png ") ', 'swf': '@ Url. Content ("~ /Content/uploadify/uploadify.swf ") ', // specify the swf file 'upload':'/Uploadify/upload', // The page 'onuploadsuccess': function (file, data, response) {eval ("data =" + data); alert ('file' + file. name + 'has been uploaded successfully, and return' + response + 'to save the file name as' + data. saveName );}});
});
Set the size of the uploaded Image

ASP. net mvc by default, the maximum size of files allowed to be uploaded is 4 MB. Therefore, by default, Uploadify can only upload up to 4 MB files. If the range is exceeded, an IO error is reported, indicating that the file cannot be uploaded.

Modify Web. config to set the maximum file size that can be uploaded:

<System. web> <! -- Set the maximum size of the file to be uploaded to 1 GB --> 

Add a system. webServer Node

<System. webServer>
<Security>
<RequestFiltering>
<! -- Modify the maximum length allowed by the server -->
<RequestLimits maxAllowedContentLength = "1073741824" type = "codeph" text = "/codeph"/>
</RequestFiltering>
</Security>
</System. webServer>

Note: The default setting in IIS7 limits the upload size. In this case, the size setting in Web. Config becomes invalid.

You can set it as follows:

1. Open the IIS manager and find the Default Web Site. Stop the service first.

2. Double-click "request filtering" in IIS.

3. Click "Edit function Settings" on the right side to open the "Edit request filter settings" dialog box.

The maximum allowed capacity length is "30000000" by default, 30 M. modify it to the size you need.

4. Start IIS.

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.