File upload--Memory overflow (system.outofmemoryexception)

Source: Internet
Author: User

Two weeks ago I want to record this experience, because of procrastination, until just suddenly think of this unfinished task, today is 1024, on this special day, I wish all the program Ape brothers and sisters Happy Holidays!

Upload function has been very normal, until the upload of more than 500 megabytes of files, error message:

An exception of type "System.OutOfMemoryException" occurs in mscorlib.dll, but is not processed in user code

For internal purposes and new managed objects, make sure that you have enough memory to allocate.
If you want to create an array, make sure the size is correct.

Because the file upload method parameter in the called WebService is in binary format, the file stream needs to be converted to byte format, so the byte[] byte = new Byte[stream is written directly. Length], the result that the big file is stuck in this sentence, the beginning is also very blindfolded, has changed the length of the maximum request in the configuration file why there is still a problem, the debug code found new byte[] in parentheses requires that the parameter is a 8-bit integer, The 500-megabyte file converted to bytes is a 9-digit number, causing the byte type to go out of the index, so that each time a fixed-length byte is instantiated, let the file loop write, write full a byte to put into the array, and then on the server to parse the array, so there is no memory overflow problem, Here is the sample code, for reference only, to take away, welcome forward.

The script section has the code shown in the previous article, which shows only the backend and the server code.

1. General Procedure section:

 Public voidFileUpload (HttpContext context) {WebService ws=NewWebService (); Usl Timeout=3600000;//unit milliseconds, 1 hourshttpfilecollection Files=context.        Request.Files; if(Files. Count >0)        {            /*get the real file name, Files[0]. FileName This method uploads in IE browser with f://path*/            stringfilename = System.IO.Path.GetFileName (files[0].            FileName); Httppostedfile file= files[0]; Stream FS=file.            InputStream; /*defines an object array to hold the byte data*/            Object[] obj =New Object[] { }; List<Object> list =Newlist<Object>(); intOffcount =1048576;/*Size:1m,unit:byte*/            intLimitsize =157286400;/*Limit size 150m,unit:byte*/            if(FS. Length >limitsize) {context. Response.Write ("outofsize"); Context.                Response.End (); return; }            intFileLen = (int) fs.            Length; if(FileLen >Offcount) {                Longoffset =0; byte[] Postarray =New byte[Offcount]; intTemponum = FileLen/Offcount; /*Integer Part*/                 for(inti =1; I <= temponum; i++)                {                    LongLKL =FileLen; Postarray=New byte[Offcount]; Fs.                    Seek (offset, seekorigin.begin); Fs. Read (Postarray,0, Offcount); List.                    ADD (Postarray); Offset+=Offcount; }                /*remaining parts*/                if(Temponum * Offcount <FileLen) {Offcount= Filelen-temponum *Offcount; byte[] Lpostarray =New byte[Offcount]; Fs.                    Seek (offset, seekorigin.begin); Fs. Read (Lpostarray,0, Offcount); List.                ADD (Lpostarray); }            }            Else            {                byte[] Postarray =New byte[File.                ContentLength]; Fs. Read (Postarray,0, file.                ContentLength); List.            ADD (Postarray); }            /*List collection to object array*/obj=list.            ToArray (); Fs.            Flush (); Fs.            Close (); /*calculate file size, file larger than 1M, unit in M, others in KB*/            stringFileSize =string.            Empty; if(FileLen >1048576) {filesize= Math.ceiling ((Double) FileLen/(Double)1024x768/ (Double)1024x768) +"M"; } Else{filesize= Math.ceiling ((Double) FileLen/(Double)1024x768) +"KB"; } /*to prevent flow length overflow byte, a fixed byte size is placed in the object array*/            stringresult = Ws.objuploadfile (obj,"Filefolder", filename); }    }

2.webservice Service-side section:

 // <summary>    ///Uploading Files/// </summary>    /// <param name= "obj" >segmented byte[] array</param>    /// <param name= "path" >File storage Folder</param>    /// <param name= "FileName" >file name</param>        /// <returns>path to the file</returns>[WebMethod (Description ="upload file, return path")]     Public stringObjuploadfile (Object[] obj,stringPathstringfileName) {        stringReturnpath =string.        Empty; FileStream WF=NULL; byte[] FS; Try        {            string_filename =string.            Empty; stringFilePath ="uploadfiles\\document\\"+path; FilePath=Server.MapPath (FilePath); if(!directory.exists (FilePath))            {directory.createdirectory (FilePath); } system.random Rnd=NewSystem.Random (); stringTMP = rnd. Next (999999999).            ToString (); _filename="File_"+ tmp +"_"+ FileName;//filename plus random numberWF =NewFileStream (FilePath +"\\"+_filename, Filemode.append, FileAccess.Write); if(obj. Length >0)            {                 for(inti =0; I < obj. Length; i++) {FS= (byte[]) obj[i]; Wf. Write (FS,0, FS.                Length); }} WF.            Close (); WF=NULL; Returnpath="\\uploadfiles\\document\\"+ Path +"\\"+_filename; }        Catch{Returnpath=string.        Empty; }        finally        {        }        returnReturnpath; }

I hope this article can help the students who meet the same problem, if there is something wrong, please correct me.

File upload--Memory overflow (system.outofmemoryexception)

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.