Upload file using web serviceIn this article I am going to show you that how to upload or transfer a file to web server by web service.
Web Service
///
/// This function is used to upload a file to server it take filename, buffer array and offset as parameter.
///
[WebMethod(Description = "Upload Resume to Server")]
public bool UploadFile(string fileName, byte[] buffer, long Offset)
{
bool retVal = false;
try
{
string FilePath = @"d:\doc\"+(fileName); //here you can specify path to store file
if (Offset == 0) // new file, create an empty file
File.Create(FilePath).Close();
// open a file stream and write the buffer.
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)
{
retVal = false;
}
return retVal;
}
Consuming Web Service
To comsume this web service, firstly add web reference of this service then create a form with a file upload server control and finally write following code on submit button
//the file that we want to upload
string FilePath = fuResume.PostedFile.FileName;
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 object of our webservice class. In my case it is DocumentAttachment class.
DocumentAttachment wsDocAttach = new DocumentAttachment();
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
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,
bool ChunkAppened = wsDocAttach.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
}
lblMsg.Text="Your resume uploaded successfully.";
}
catch (Exception ex)
{
lblMsg.Text = "Some error occured during uploading resume.";
}
finally
{
fs.Close();
}
That's all use it.