Arka
Arka

Reputation: 31

How to get PDF back from a byte array

What I’m trying to do is…

Let the user select a PDF file and some other files using a WCF…once they select the file…those files need to be moved from there to a remote server (company hosted). I’m trying to deserialize the data (reading it as bytes) and transferring it over. I created a Form just as a testing purpose and to see how my client is going to work.

When I get the file....I can display the file but I want to get the actual PDF back and I’m not being able to do that. I can open the file in notepad (but its in the byte format) and when I try to open it in PDF it says that the file format is not supported. I’m really confused and don’t know what needs to be done.

Your help will be really appreciated.

Code Snippet:

Client Side:

    private void btnUploadFile_Click(object sender, EventArgs e)
            {
            string pathServer = @"C:\Users\....\Desktop\Test.pdf";

            RestClient newClient = new      RestClient("http://localhost:...../Service1.svc/DisplayRawData");
            var request = new RestRequest(Method.GET);
            request.RequestFormat = DataFormat.Json;
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
            IRestResponse<TempString> newResponse = newClient.Execute<TempString>(request);
            //List<TempString> rtrn = (List<TempString>)newResponse.Data;     
            var responseData = newClient.DownloadData(request);

            FileStream fStream = new FileStream(pathServer, FileMode.Create);

            BinaryWriter bw = new BinaryWriter(fStream);

            bw.Write(responseData);
            bw.Close();

            foreach (var xbyte in responseData)
            {
               // fStream.WriteByte(xbyte); 

            }

            //fStream.Flush();
            fStream.Close(); 

Server Side (Service)

public string DisplayRawData()
        {
            string path = @"C:\basketball.pdf";
            byte[] fileToSend = File.ReadAllBytes(path);
            string filetoSendB64 = Convert.ToBase64String(fileToSend);
           // WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";

            return filetoSendB64;
        }

Interface

        //Getting Stream from a File
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "DisplayRawData",
                    RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

        // string DisplayRawData();

        string DisplayRawData();

Upvotes: 0

Views: 2160

Answers (1)

Tim B
Tim B

Reputation: 2368

The code is a bit confusing, but I would say it looks like you need to decode the response string from Base64 back to a byte array before writing it to a file.

Upvotes: 1

Related Questions