Click here to Skip to main content
Click here to Skip to main content

Uploading Large Files Through Web Service

By , 25 Oct 2009
 

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.

/// <summary>
/// This function is used to append chunk of bytes to a file name. 
/// If the offset starts from 0 means file name should be created.
/// </summary>
/// <param name="FileName">File Name</param>
/// <param name="buffer">Buffer array</param>
/// <param name="Offset">Offset</param>
/// <returns>boolean: true means append is successfully</returns>
[WebMethod]
public bool UploadFile(string FileName, byte[] buffer, long Offset)
{
bool retVal = false;
try
{
// setting the file location to be saved in the server. 
// reading from the web.config file 
string FilePath = 
	Path.Combine(ConfigurationManager.AppSettings["upload_path"], FileName);

if (Offset == 0) // new file, create an empty file
File.Create(FilePath).Close();
// open a file stream and write the buffer. 
// Don't open with FileMode.Append because the transfer may wish to 
// start a different point
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)
{
//sending error to an email id
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:

//the file that we want to upload
string FilePath="d:\somefile.pdf";
int Offset = 0; // starting offset.

//define the chunk size
int ChunkSize = 65536; // 64 * 1024 kb

//define the buffer array according to the chunksize.
byte[] Buffer = new byte[ChunkSize];
//opening the file for read.
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
//creating the ServiceSoapClient which will allow to connect to the service.
WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
try
{
long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
// reading the file.
fs.Position = Offset;
int BytesRead = 0;
while (Offset != FileSize) // continue uploading the file chunks until offset = file size.
{
BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the next chunk 
	// (if it exists) into the buffer. 
	// the while loop will terminate if there is nothing left to read
// check if this is the last chunk and resize the buffer as needed 
// to avoid sending a mostly empty buffer 
// (could be 10Mb of 000000000000s in a large chunk)
if (BytesRead != Buffer.Length)
{
ChunkSize = BytesRead;
byte[] TrimmedBuffer = new byte[BytesRead];
Array.Copy(Buffer, TrimmedBuffer, BytesRead);
Buffer = TrimmedBuffer; // the trimmed buffer should become the new 'buffer'
}
// send this chunk to the server. it is sent as a byte[] parameter, 
// but the client and server have been configured to encode byte[] using MTOM. 
bool ChunkAppened = soap_client.UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
if (!ChunkAppened)
{
break;
}

// Offset is only updated AFTER a successful send of the bytes. 
Offset += BytesRead; // save the offset position for resume
}
}
catch (Exception ex)
{
}
finally
{
fs.Close();
}

History

  • 25th October, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

hussain.attiya
Architect Atyaf Telecommunication - Bahrain
Bahrain Bahrain
Current Position is : ISP Technical Manager
 
Leading a Team of Developers for developing ecommerce websites and systems integration using several integration methods such as XML.
 
Manage ISP infrastructure, web servers, database servers, application servers, email servers and networks. Design the architecture of complex web applications; build web applications in JAVA, asp, asp.Net; manage web sites including networking and database; experienced in MS Sql Server and Oracle;
 
stay current with emerging trends and technological advances in the industry.
 
MCTS,MCAD VB.NET, ASP.NET and XML Services,BTEC National Diploma in Computer Studies.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionMy vote of 5 PinmemberGeorge Serbanescu18-Mar-13 1:19 
My vote of 5
GeneralMy vote of 4 PinmemberPallenov6-Feb-13 9:58 
It is clear and short
QuestionDeployment of solution PinmemberLaurentiu LAZAR4-Dec-12 23:22 
Hi,
 
I tested a solution based on the article. The solution consist obvious in two projects:
an web service and
a web application that consume the service.
When I debug from Visual Studio al is OK and the file is uploaded. But when I deploy on an internal staging server, the web service seems to do nothing (it does not throw errors, or I don't know how to catch them in web app an display them, but the file is not uploaded).
More of this, this not clear to me how to implement this in a way that upload a file from my client computer (e.g. my develop notebook) to the server. My perception is that it uploads a file from the machine where the web app and web server resides (e.g. the staging server).
On short, I need to programmatically upload a file from folder c:\source_folder\ from my notebook to c:\destination_folder on my server
 
thanks
Questionregarding namespace to be included Pinmembervijayalaya7-Nov-12 20:39 
hi,
I have copy/pasted your code and am getting error in the below line
WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
 
Could you pleae let me know the namespace to be added or reference to be added to solve this.
I have conveted the above source lines to vb.net codebehind.
 
Thanks in Advance
Vijay
GeneralMy vote of 4 PinmemberHarshit Raj Singh21-Oct-12 11:35 
Vote 4 of 5
QuestionAn attempt was made to move the file pointer before the beginning of the file Pinmembertungkhac10-Oct-12 23:15 
every time that occur exception 'An attempt was made to move the file pointer before the beginning of the file' when file transferred 2gb. I was tried to upload file large 3gb. Please help me to resolve problem
QuestionReg. Upload files which are of 10 GB PinmemberErukulla vijay18-Dec-11 18:36 
Hi,

I am using Visual studio 2008. My requirement is to upload the files which are of size <= 10 GB. Is it possible with this code..? If not, Can you please let me know the alternate solution for this..?
 
If your code is suitable to my requirement,Can you please let me know how can i do this in a Web Project..
 
Thanks & Regards,
Vijay Kumar E.
GeneralMy vote of 5 PinmemberLuiz Carvalho13-Dec-11 18:13 
Very nice. You save me!
GeneralMy vote of 4 PinmemberRamanjaneyulu Kondaru8-Nov-11 1:16 
Nice article
GeneralGreat! PinmemberKantabriko17-Nov-10 14:25 
Great solution!
 
I've been looking for something like this for some weeks.
 
I translate your code to VB.NET and it works!
 
Thanks!!!
QuestionCould you post a sample project? PinmemberRui Frazao16-Jun-10 23:39 
Could you post a sample project?
Thanks
GeneralHi PinmemberRavenet27-Oct-09 15:06 
Hi
 
Could i have your direct contact email id?
 
thank you
 
RRave
MCTS,MCPD
All experts are welcome to http://codegain.com
 

 

GeneralRe: Hi Pinmemberhussain.attiya27-Oct-09 19:31 
GeneralRe: Hi PinmemberRavenet28-Oct-09 3:48 
GeneralRe: Hi PinmemberRavenet28-Oct-09 3:53 
GeneralMy vote of 1 PinmentorMark Nischalke26-Oct-09 5:43 
How did this even get approved?
 
Poorly formatted, no explanation of the code, and a topic that needs no more discussion
GeneralRe: My vote of 1 Pinmemberhussain.attiya26-Oct-09 23:14 
AnswerWeb services are converting bytes array to 64 base PinmemberErezAlster25-Oct-09 4:22 
you are sending 0.3 precent more than the actual file size.
 
Another solution is to right dedicated pages that know how to handle Http Request.
The parameters can be sent with the Http headers and bytes array in the content of the http request.
 
Good luck,
Erez

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 25 Oct 2009
Article Copyright 2009 by hussain.attiya
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid