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();
                        }                  
                    });

这是 wcf 代码,我在其中从字符串中的 jquery 和文件对象检索数据并转换为流。使用下面的代码我可以存储文件,但字节存储不正确。请尽快告诉我有什么问题。

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

0 回答 0