1
    Hello All,
      how i can upload file using jquery ajax i am trying to send this parameter to wcf rest service but its not working. 

here is the ajax code where i am passing file name and file object.


enter code here

  $.ajax({
            url: "http://localhost:1340/b/SaveProjectDocument/" + file.name + "/" + file,
                        data: null,
                        type: "POST",
                        contentType: "application/javascript",
                        dataType: "jsonp",
                        error: function () {
                            alert("Failed!");
                        },
                        success: function () {
                            $("#divLoadingEdit").hide();
                        }                  
                    });

here is the wcf code where i am retrieving data from jquery and file object in a string and convert into stream. using below code i can store file but the byte are storing not correct. please advice me what is wrong with it asap.

[WebInvoke(Method = "POST",
                   ResponseFormat = WebMessageFormat.Json,
                  UriTemplate = "SaveProjectDocument/{filename}/{fileContents}")]
 public void SaveProjectDocument(string filename, string fileContents)
        {
            try
            {
//converting string into stream.
                //byte[] byteArray = Encoding.UTF8.GetBytes(fileContents);
                byte[] byteArray = Encoding.ASCII.GetBytes(fileContents);
                MemoryStream stream = new MemoryStream(byteArray);

//reading stream and assign new memory to byte array.
                byte[] buffer = new byte[stream.Length];               
                int count = 0;
                FileStream fileToupload = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/Files/") + filename, FileMode.Create, FileAccess.ReadWrite);
                while (count < stream.Length)
                {
                    buffer[count++] = Convert.ToByte(stream.ReadByte());
                }

                fileToupload.Write(buffer, 0, buffer.Length);
                fileToupload.Close();
                fileToupload.Dispose();


            }
            catch (Exception ex)
            {`enter code here`
                ///return 0;
            }
        }
user2319413
  • 31
  • 1
  • 5
  • 1
    I'm trying to figure this out myself, but I don't *think* you can pass the fileContents in via the UriTemplate. I *think* you either have to use Silverlight/Flash or send the File Contents up via an HTML Form. If you send the contents up via an HTML Form, I think you have to acquire or implement a Multipart Form Parser to use in your WCF Service as demonstrated in both of these posts: http://stackoverflow.com/questions/9734941/upload-file-from-html-form-multipart-form-data-to-wcf-rest-service-as-a-stream or http://antscode.blogspot.com/2009/11/parsing-multipart-form-data-in-wcf.html – Shawn Eary Sep 15 '13 at 23:10

0 Answers0