PokeRwOw
PokeRwOw

Reputation: 599

WCF/C# upload a file

I'm currently working on a web service with C# and WCF. I need to make a upload method so I following this tutorial. Now I can upload file through the form and the file is uploaded in the folder but in the browser It's always return me that there is an error (like specified in the ajax) Here all the code :

IWebService.cs

[ServiceContract]
public interface IWebService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
    void UploadFile(string fileName, Stream stream);
}

WebService.svc

public void UploadFile(string fileName, Stream stream)
{
    string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), fileName);

    int length = 0;
    using (FileStream writer = new FileStream(FilePath, FileMode.Create))
    {
        int readCount;
        var buffer = new byte[8192];
        while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            writer.Write(buffer, 0, readCount);
            length += readCount;
        }
    }
}

TestClient.html

<head>
<script type="text/javascript">
    function UploadFile() {
        fileData = document.getElementById("fileUpload").files[0];
        var data = new FormData();

        $.ajax({
            url: 'http://localhost:1945/Service1.svc/UploadFile?fileName=' + fileData.name,
            type: 'POST',
            data: fileData,
            cache: false,
            dataType: 'json',
            processData: false, // Don't process the files
            contentType: "application/octet-stream", // Set content type to false as jQuery will tell the server its a query string request
            success: function (data) {
                alert('successful..');
            },
            error: function (data) {
                alert('Some error Occurred!');
            }
        });
    }

</script>
<title></title>
</head>
<body>
<div>
    <div>
        <input type="file" id="fileUpload" value="" />
        <br />
        <br />
        <button id="btnUpload" onclick="UploadFile()">
            Upload
        </button>
    </div>
</div>
</body>

Upvotes: 0

Views: 2420

Answers (1)

agit
agit

Reputation: 631

I was try to solve your problem in my way

  1. Change the retun type of UploadCustomFile method to String and return a dummy message

    public String UploadCustomFile(string fileName, System.IO.Stream stream) { string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), fileName);

    int length = 0;
    using (FileStream writer = new FileStream(FilePath, FileMode.Create))
    {
        int readCount;
        var buffer = new byte[8192];
        while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            writer.Write(buffer, 0, readCount);
            length += readCount;
        }
    }
    
        try
        {
            //do something else
        }
        catch
        {      
                //to return custom error message - ajax will catch this as a error
                HttpContext.Current.Response.Write("");
                return "not okey";
        }
    
    return "okey";
    }
    
  2. Change interface method by adding ResponseFormat = WebMessageFormat.Json and String return type

    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
    String UploadCustomFile(string fileName, Stream stream);
    

When i tried this way, i got success alert message

To send custom exception from server side

Upvotes: 2

Related Questions