Uploading a file to WCF service using HTML5 and/or

2020-07-10 05:14发布

问题:

I am trying to upload a file to my WCF service using only HTML5 and JavaScript/jQuery. The WCF service is self hosted from a Windows service instead of IIS, so I don't think I can use php or aspx upload handlers. The files are binary and not text.

Ideally, I would like to end up with a .net stream object where I can write the file locally (server side). At this point I'm just looking for very very basic file uploading.

I can do JSON communication currently, but cant make the leap to binary files. Currently I'm this far and stuck:

Service interface:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "SendFile")]
string SendFile(Stream stream);

Service Implementation:

public string SendFile(Stream stream)
        {
            // this works for strings, but i want a FileStream
            StreamReader reader = new StreamReader(stream);
            string data = reader.ReadToEnd();

            return data;
        }

HTML:

 <input type="file" id="fileInput" onchange='sendFile();' />

JavaScript / jQuery:

 function sendFile() {
        submitButton.disabled = true; ;
        setInnerText("sending file...");
        var file = document.getElementById('fileInput').files[0];
        var url = "http://10.0.1.9:8732/RainService/SendFile";
        $.ajax({
            url: url,

            type: "POST",
            data: file,
        });
    }

In the Chrome console I get an "Illegal invocation" error. I could use data: file.name and that would work fine however. I need to send a stream of the file contents so i can rebuild it on the server side.

Any ideas?

回答1:

you cannot send file through ajax. You have to use a plugin which has SWF object integrated where you can upload some file type (you define what).

So, I can suggest you to use uploadify (I used it into my project with MVC3).

Or you can use: http://www.codeproject.com/KB/WCF/WCFDownloadUploadService.aspx

or

http://www.codeproject.com/KB/WCF/UploadlargeFilesWCFHTTP.aspx for more documentation

Of course, google can help you more



标签: jquery ajax wcf