Introduction
In this article, I am going to explain how to upload large files using web service method. We will not need to change anything in IIS or web.config (maximum request size) developed in Visual Studio 2008.
Using the Code
I have created a web method to accept file name, bytes (array) and offset. Here is the function.
[WebMethod]
public bool UploadFile(string FileName, byte[] buffer, long Offset)
{
bool retVal = false;
try
{
string FilePath =
Path.Combine(ConfigurationManager.AppSettings["upload_path"], FileName);
if (Offset == 0) File.Create(FilePath).Close();
using (FileStream fs = new FileStream(FilePath, FileMode.Open,
FileAccess.ReadWrite, FileShare.Read))
{
fs.Seek(Offset, SeekOrigin.Begin);
fs.Write(buffer, 0, buffer.Length);
}
retVal = true;
}
catch (Exception ex)
{
common.SendError(ex);
}
return retVal;
}
In the function, I am setting the file location to be saved in the server. I have put it in a appSetting section in the web.config file.
<add key="upload_path" value="d:\files\"></add>
How to Consume the Web Method
I have created a Windows application (C#). I have put a button. On the button click, I have put the following code:
string FilePath="d:\somefile.pdf";
int Offset = 0;
int ChunkSize = 65536;
byte[] Buffer = new byte[ChunkSize];
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
try
{
long FileSize = new FileInfo(FilePath).Length; fs.Position = Offset;
int BytesRead = 0;
while (Offset != FileSize) {
BytesRead = fs.Read(Buffer, 0, ChunkSize); if (BytesRead != Buffer.Length)
{
ChunkSize = BytesRead;
byte[] TrimmedBuffer = new byte[BytesRead];
Array.Copy(Buffer, TrimmedBuffer, BytesRead);
Buffer = TrimmedBuffer; }
bool ChunkAppened = soap_client.UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
if (!ChunkAppened)
{
break;
}
Offset += BytesRead; }
}
catch (Exception ex)
{
}
finally
{
fs.Close();
}
History
- 25th October, 2009: Initial post