Thomas
Thomas

Reputation: 34218

How to develop web service (ASMX) for uploading file with status

uploading file to web server with the help of web service is easy. this is the way i do it generally. here is my sample code.

[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;
}

but i want to develop web service which will give me status for uploading file in percentage and when file upload will be completed then a event will be fired at client side with status message whether file is uploaded completely or not. also i need to write routine which can handle multiple request simultaneously and also routine must be thread safe. so please guide me how to design routine which will suffice all my require points. thanks

Upvotes: 0

Views: 2115

Answers (1)

Rick Strahl
Rick Strahl

Reputation: 17681

I'd highly recommend that you forget about implementing this from scratch and instead look into one of the existing client file upload solutions that are available - most come with some boilerplate .NET code you can plug into an existing application.

I've used jQuery Upload and plUpload both of which have solid client side upload managers that upload files via HTTP Range headers and provide upload status information in the process. I believe both come with .NET examples.

Implementation of the server side for these types of upload handlers involve receiving HTTP chunks of data, that are identified via a sort of upload session id. The client sends chunks of files, each identified by this file related id as well as some progress information like bytes transferred and total file size and a status value that inidicates the status of the request. The status lets you know when the file is completely uploaded.

The incoming data from the POST buffer can then be written to a file or into a database or some other storage mechanism based on the unique ID passed from the client. Because the client application is sending chunks of data to the server it can provide progress information. If you use a client library like plUpload or jQuery-Upload they'll provide the customizable UI.

Upvotes: 2

Related Questions