Задайте вопросЗадайте вопрос
 

Предложенный ответWCF - File Uploading

  • 11 сентября 2008 г. 7:39jd12215 Медали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     
    I have been trying to create a WCF web service that would allow uploading different files to the web server. There doesn't seem to be much out there with regards to file uploading and WCF but I did manage to find ueira post on "receiving arbitrary data" and went ahead and implement the custom binding to accept RAW. This worked, but still got problems.

    I can upload a file (png, pdf, txt, whatever), write the stream using FileStream.write() but when I try to open it there are errors. Images and PDF's don't show and txt files always show the multipart/form-data boundaries.

    My questions are:

     - Why don't examples like Kjells work with binary data (content-type => application/octet-stream)?
     - When using Carlos' custom binding, why are the boundaries being added to the file when written to disk? Am I not implementing the file save correctly?

    I've seen some examples that use Byte arrays instead of Streams but Microsofts articles seem to suggest that streaming is the way to go.

     SaveFile():
    Code Snippet

           public void SaveFile(string fileName, Stream logFile)
            {
                if (!uploadDirectory.EndsWith("\\"))
                    uploadDirectory += "\\";

                WebOperationContext ctx = WebOperationContext.Current;


                try
                {
                    FileStream fs = null;
                    /* USE STREAMING */

                    using (fs = new FileStream(uploadDirectory + fileName, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        const int bufferLen = 1024; //read stream @ 4K chunks
                        byte[] buffer = new byte[bufferLen];

                        int bytesRead = 0;
                        while ((bytesRead = logFile.Read(buffer, 0, bufferLen)) > 0)
                        {
                            fs.Write(buffer, 0, bytesRead);
                            ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Continue;
                        }

                        fs.Close();
                        logFile.Close();

                        ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                        return;
                    }
                }
                catch (IOException ex)
                {
                    throw ex;
                }
            }


Все ответы