将文件从网页上传到服务器时遇到问题。它适用于高达 200 MB 的文件,但开始抛出内存异常。你能帮我吗?我已经粘贴了下面的代码
private void UploadToServer(HttpPostedFile oHttpPostedFile)
{
string CalCheckSum = string.Empty;
try
{
string FileName = getFileName(oHttpPostedFile.FileName.Trim());
if (File.Exists(Server.MapPath("Upload") + "\\" + System.IO.Path.GetFileName(FileName)))
{
File.Delete(Server.MapPath("Upload") + "\\" + System.IO.Path.GetFileName(FileName));
}
string serverFilePath = Server.MapPath("Upload") + "\\" + System.IO.Path.GetFileName(FileName);
FileStream fs = new FileStream(serverFilePath, FileMode.CreateNew);
string strFileFormName = serverFilePath;
// Uri oUri = new Uri(strUrl);
// DFB: Upload goes into stream
Stream myStream = oHttpPostedFile.InputStream;
string _name = oHttpPostedFile.FileName;
string _contentType = oHttpPostedFile.ContentType;
// DFB: Create buffer for stream
Byte[] myBuffer;
myBuffer = new byte[10240];
if (myStream.Length == 0)
{
//Zero Bytes file Can not be processed
CalCheckSum = string.Empty;
return;
}
else if (myStream.Length > 10240)
myBuffer = new byte[10240];
else
myBuffer = new byte[myStream.Length];
StringBuilder filecontent = new StringBuilder();
int fileLength = (int)myStream.Length;
int length = (int)myStream.Length / myBuffer.Length + 1;
int lastPacketLength = (int)myStream.Length % 10240;
int count = 1;
while (myStream.Read(myBuffer, 0, myBuffer.Length) > 0)
{
if (count == length)
fs.Write(myBuffer, 0, lastPacketLength);
else
fs.Write(myBuffer, 0, myBuffer.Length);
count++;
}
fs.Close();
fs.Dispose();
myStream.Dispose();
myBuffer = null;
myStream = null;
FileStream fileStream = File.OpenRead(serverFilePath);
byte[] pbytCombinedArrays = new byte[fileLength];
int numBytesToRead = fileLength;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fileStream.Read(pbytCombinedArrays, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
fileStream.Dispose();
fileStream.Close();
}