C# – Upload file using asp.net webservice

asp.netcweb services

Hello I want to upload file from webservice not WCF.I am using C# and consuming it with web application.From web application send file,and service will accept that file(text file) and place in upload folder of website/or specific location.

For this I have created webservice like this

: For making webservice

Created empty web application -> selected new Item -> Web service

1> Wrote following code in webservice

public System.IO.Stream FileByteStream;
[WebMethod]
public void UploadFile()
{ 
FileStream targetStream = null;

Stream sourceStream = FileByteStream;

string uploadFolder = @"D:\UploadFile";

string filePath = Path.Combine(uploadFolder, @"C:\Users\maya\Desktop\test.txt");

using (targetStream = new FileStream(filePath, FileMode.Create,
FileAccess.Write, FileShare.None))
{
    //read from the input stream in 65000 byte chunks
    const int bufferLen = 65000;
    byte[] buffer = new byte[bufferLen];
    int count = 0;
    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
    {
        // save to output stream
        targetStream.Write(buffer, 0, count);
    }
    targetStream.Close();
    sourceStream.Close();
}

Here my not taking any input,I have manual entered one text file.I want to transfer that file to uploadfolder. I am getting this error:

HTTP 500 Internal server error

at this line:

while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)

How to handle this?

Best Answer

I use an aspx page instead of a webservice.I use jquery to do so. It works like a charm.

so let this be your file upload control.

<div>  
<input type="file" name="UploadFile" id="txtUploadFile"   />
</div> 

Here is jquery code

$('#txtUploadFile').on('change', function (e) {
var files = e.target.files;
if (files.length > 0) {
   if (window.FormData !== undefined) {
       var data = new FormData();
       for (var x = 0; x < files.length; x++){
           data.append("file" + x, files[x]);
       }

       $.ajax({
           type: "POST",
           url: '/Upload.aspx', //put the complete url here like http://www.example.com/Upload.aspx
           contentType: false,
           processData: false,
           data: data,
           success: function(result) {
               console.log(result);
           },
           error: function (xhr, status, p3, p4){
               var err = "Error " + " " + status + " " + p3 + " " + p4;
               if (xhr.responseText && xhr.responseText[0] == "{")
                   err = JSON.parse(xhr.responseText).Message;
                   console.log(err);
                }
            });
    } else {
        alert("This browser doesn't support HTML5 file uploads!");
      }
 }
});

And this is my aspx code

public partial class Upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            UploadFile(sender, e);
        }

    }
    protected void UploadFile(object sender, EventArgs e)
    {
        try
        {
            HttpFileCollection fileCollection = Request.Files;
            string savedfile = "";
            for (int i = 0; i < fileCollection.Count; i++)
            {
                try
                {
                    HttpPostedFile upload = fileCollection[i];
                    int f = fileCollection[i].ContentLength;
                    string filename = "/ProductImages/" + fileCollection[i].FileName;
                    upload.SaveAs(Server.MapPath(filename));
                    savedfile += fileCollection[i].FileName;
                }
                catch (Exception ex)
                {

                }

            }
        }
        catch(Exception ex)
        {
            List<string> ff = new List<string>();
            ff.Add(ex.Message.ToString());
            System.IO.File.WriteAllLines(Server.MapPath("/ProductImages/Error.txt"), ff);
        }

    }
}