当前位置:首页 > c# post大文件报错OutOfMemoryException 内存溢出

c# post大文件报错OutOfMemoryException 内存溢出

点击次数:4543  更新日期:2016-12-07

c#post大文件时(大于500M),会报OutOfMemoryException的错误,后来设置request.ContentLength后,文件上传上去了,但是在关闭流的时候,报错“请求被中止: 请求已被取消”,原因应该是写入的大小跟设置的大小不一样,解决的方法是写入与请求的大小相同的字节数


完整的代码如下:

//post上传文件

public static byte[] PostFile(string url, IEnumerable<UploadFile> files, NameValueCollection values)

        {

            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

                try

                {

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                    request.ContentType = "multipart/form-data; boundary=" + boundary;

                    request.Method = "POST";

                    request.KeepAlive = true;

                    request.Credentials = CredentialCache.DefaultCredentials;

                    long totallength = 0;

                    //获取文件大小

                    if (files != null)

                    {

                        foreach (UploadFile file in files)

                        {

                            FileInfo fi = new FileInfo(file.Filename);

                            totallength += fi.Length;

                        }

                    }

                    byte[] line = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                    request.ContentLength = totallength + 80960;

                    request.Timeout = 1000 * 100;

                    Stream stream = request.GetRequestStream();


                    long postlength = 0;

                    stream.WriteTimeout = 1000 * 100;




                    //提交文本字段

                    if (values != null)

                    {

                        string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

                        foreach (string key in values.Keys)

                        {

                            string s = string.Format(format, key, values[key]);

                            byte[] data = Encoding.UTF8.GetBytes(s);

                            stream.Write(data, 0, data.Length);

                            totallength += data.Length;

                        }

                        stream.Write(line, 0, line.Length);

                        postlength += line.Length;

                    }


                    //提交文件

                    if (files != null)

                    {

                        string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

                        foreach (UploadFile file in files)

                        {

                            string s = string.Format(fformat, file.Name, file.Name);

                            byte[] data = Encoding.UTF8.GetBytes(s);

                            stream.Write(data, 0, data.Length);

                            postlength += data.Length;


                            int bufferSize = 4096; //每次读取的字节数

                            byte[] buffer = new byte[bufferSize];

                            System.IO.FileStream inputstream = null;

                            int ss = 0;

                            try

                            {

                                inputstream = new System.IO.FileStream(file.Filename, System.IO.FileMode.Open);

                                long fileLength = inputstream.Length;//文件流的长度


                                int readCount = (int)Math.Ceiling((double)fileLength / bufferSize); //需要对文件读取的次数

                                int tempCount = 0;//当前已经读取的次数


                                do

                                {

                                    inputstream.Read(buffer, 0, bufferSize); //分readCount次读取这个文件流,每次从上次读取的结束位置开始读取bufferSize个字节

                                    //这里加入接收和处理数据的逻辑

                                    stream.Write(buffer, 0, buffer.Length);

                                    postlength += buffer.Length;

                                    tempCount++;

                                }

                                while (tempCount < readCount);

                            }

                            catch (Exception ex)

                            {


                            }

                            finally

                            {

                                if (inputstream != null)

                                {

                                    inputstream.Close();

                                    inputstream.Dispose();

                                }


                            }



                            stream.Write(line, 0, line.Length);

                            postlength += line.Length;

                        }


                    }


                    while (postlength < request.ContentLength)

                    {

                        stream.WriteByte(0);

                        postlength++;

                    }


                    using (var response = request.GetResponse())

                    using (var responseStream = response.GetResponseStream())

                    using (var mstream = new MemoryStream())

                    {

                        responseStream.CopyTo(mstream);

                        stream.Close();

                        return mstream.ToArray();

                    }

                }

                catch (Exception ex)

                {


                }

            return null;

        }


//UploadFile类

public class UploadFile

        {

            public UploadFile()

            {

                ContentType = "application/octet-stream";

            }

            public string Name { get; set; }

            public string Filename { get; set; }

            public string ContentType { get; set; }

        }