简体   繁体   中英

limit number of files to be uploaded in mvc

In my MVC application, i have information upload form. Here user can upload videos and images. To do this i have created to file controls, one for videos and one for images. Here user should be only able to upload at max 2 videos and at max 5 images for single form. Can any one suggest me how can i limit the user to upload number of files. ie if only 2 videos and 5 images also where should i implement this for best use? in controller or using javascript ?

The MVC file upload approach:

<input type="file" name="file" id="file" />

This passes a HttpPostedFileBase to the controller or if you have multiple IEnumerable<HttpPostedFileBase> . You can then evaluate the number of files and file types and return any functionality/messages back to the user.

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {...

Or

<input type="file" name="files" id="file" />
<input type="file" name="files" id="file" />

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {...

I tried using javascript

File upload control :

<input type="file" id="t" name="t" onchange="checkFilesCount(this)" multiple>

javascript code :

function checkFilesCount(id) {
    if(id.files.length > 5)
    {    
        alert('you cant upload files more than 5');
        document.getElementById("t").value = "";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM