About MVC uploading files

Source: Internet
Author: User

The foreground code is as follows

@{Layout = null;}<!DOCTYPE HTML><HTML><Head>    <title>Index</title>    <Scriptsrc= "@Url. Content ("~/scripts/jquery-1.5.1.min.js ")" Type= "Text/javascript"></Script>    <Scripttype= "Text/javascript">        var Times= 1; $("#add"). Click (function () {            varFilenmae= "FileUpLoad" +N; $("#divdivfile"). Append ("<input type=\ "file\" name=\ "" +Filenmae+ "\ "/>"); Times++;    }); </Script></Head><Body>    <Div>@using (Html.BeginForm ("UpLoad", "Updateload", FormMethod.Post, new {enctype= "Mutipart/form-data"})) {             <DivID= "Divfile">                <inputtype= "File"name= "FileUpload" />            </Div>            <inputtype= "button"ID= "Add"value= "Add" />            <inputtype= "Submit"ID= "Submit"value= "Upload" />        }    </Div></Body></HTML>

First determine if the uploaded file is legitimate

     Public enumfiletypeextension {GIF=7173, PNG=13780, JPG=255216,    }     Public classFileuploadcommon {/// <summary>        ///used primarily to determine whether a particular file being uploaded is bound to a specific suffix name/// </summary>        /// <param name= "Fu" >uploaded file Object</param>        /// <param name= "Fileex" >types of files that the system allows to upload</param>        /// <returns>true: The delegate passed validation, false: The delegate did not pass the validation</returns>         Public Static BOOLisallowedextension (HttpPostedFileBase fu, filetypeextension[] Fileex) {intContentLength =Fu.            ContentLength; byte[] buffer =New byte[ContentLength]; Fu. Inputstream.read (Buffer,0, contentlength); MemoryStream input=NewMemoryStream (buffer); BinaryReader Reader=NewBinaryReader (input); strings =""; Try{s=Reader. ReadByte ().                ToString (); S= S +Reader. ReadByte ().            ToString (); }            Catch{} reader.            Close (); Input.            Close (); foreach(filetypeextension extensioninchFileex) {                if(int. Parse (s) = =convert.toint32 (extension)) {                    return true; }            }            return false; }    }

Background code is divided into a single upload and batch upload, note that part of the bulk upload

[HttpPost] [ValidateInput (false)]         PublicActionResult UpLoad (Formmodel model) {filetypeextension[] Filetypearr={filetypeextension.gif, filetypeextension.jpg, filetypeextension.png}; //Single Upload            Try            {                if(Request.Files! =NULL&& Request.Files.Count >0&& request.files[0]. ContentLength >0)                {                    stringFileType = request.files[0]. ContentType;//Get file TypeStream FileStream = request.files[0].                    InputStream; BOOLFileOk = Fileuploadcommon.isallowedextension (request.files[0], Filetypearr);//determine if the uploaded file is legitimate                    if(FileOk && request.files[0]. ContentLength/1024x768<1024x768)//determine legality and file size is legal                    {                        stringPath = Server.MapPath ("/content/fileupdateload/"); stringFileName = Path.getfilenamewithoutextension (request.files[0]. FileName) + DateTime.Now.ToString ("YYYYMMDDHHMMSS") +FileType; request.files[0].                        SaveAs (Path.Combine (Path, fileName)); return redirecttoaction ("Index", "updateload");
} ElseViewbag.error="file is too large or not properly formatted"; } ElseViewbag.error="failed to upload file, you may not have chosen to upload the file"; } Catch(Exception ex) {Viewbag.error="uploading the file failed for the following reasons:"+Ex. Message; } //foreach (string upload in Request.Files)//if it is a bulk upload//{ //if (upload! = null && request.files[upload]. ContentLength > 0)// { //string fileType = Request.files[upload]. ContentType; //Get file Type//Stream fileStream = request.files[upload]. InputStream; //bool fileOk = Fileuploadcommon.isallowedextension (Request.files[upload], Filetypearr); //determine if the uploaded file is legitimate//if (fileOk && request.files[upload]. contentlength/1024 < 1024x768)//determine legality and file size is legal// { //string path = Server.MapPath ("/content/fileupdateload/"); //string fileName = Path.getfilenamewithoutextension (Request.files[upload]. FileName) + DateTime.Now.ToString ("Yyyymmddhhmmss") + FileType; //Request.files[upload]. SaveAs (Path.Combine (Path, fileName)); // } //Else//viewbag.error = "file is too large or not properly formatted"; // } //else continue; //} returnView (model);
}

About profile limits upload file size and upload time

    " maxrequestlength="2048000  " usefullyqualifiedredirecturl="false"/>  </ System.web>

 

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.