Wednesday 26 July 2017

Bytes save and download as PDF in web API


In this obj.ValueType is a base 64 data Firstly we have to convert base 64 into Byte[] after that save in a folder or also direct download without saving the pdf file.


  public HttpResponseMessage updateprofileImage(info obj)
        {
            var httpRequest = HttpContext.Current.Request;
            string fileOriginalPath = "~/FileUploaded";
            var file64 = obj.ValueType;// httpRequest.Form[0];

            string strTutorImg = string.Empty;

            if (!string.IsNullOrEmpty(file64))
            {
                /*where you need to save 64 file*/
                string Base64file;
                Base64file = DateTime.UtcNow.Ticks + "-" + "base64-" + "decod.pdf";
                var filepath1 = httpRequest.MapPath(fileOriginalPath);
                /*end here */

                /*Convert base64 file into pdf file start here*/
                Byte[] bytes2 = Convert.FromBase64String(file64);

                //save into folder
                filepath1 = Path.Combine(filepath1, System.IO.Path.GetFileName(Base64file));
                File.WriteAllBytes(filepath1, bytes2);

                //direct download 
                HttpContext.Current.Response.Clear();
                MemoryStream ms = new MemoryStream(bytes2);
                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition",                 "attachment;filename=labtest.pdf");
                HttpContext.Current.Response.Buffer = true;
                ms.WriteTo(HttpContext.Current.Response.OutputStream);
                HttpContext.Current.Response.End();

             
                /*End here*/

                /*if you need to save this base64 into database so save this variable value=>   file64*/

            }
            return Request.CreateResponse(HttpStatusCode.OK, file64); ;
        }

No comments:

Post a Comment