简体   繁体   中英

image to base64 in javascript and c# (frontend and backend) is different

I am trying to convert an image to base64 to upload it on sharepoint site but it is throwing 400:bad request error. when i checked properly then i found out that the base64 i am sending is endcoded by javascript and it is different than what is expected by sharepoint. I have attached 2 images here describing the difference. Can anyone help me to get the proper encoded data using javascript ?

javascript encoded base64

c# encoded base64

var files = $("#myfile").get(0).files;

        var reader = new FileReader();
        reader.readAsDataURL(files[0]);

        reader.onload = function () {
          console.log(reader.result);
        }

Could try : reader.result.split("base64,")[1]

Removes the "base64," start of the string.

    Please try this , i am using this in my project , its working for me



     if (file.ContentType.Contains("image"))
                {
                    string theFileName = Path.GetFileName(file.FileName);
                    byte[] thePictureAsBytes = new byte[file.ContentLength];
                    using (BinaryReader theReader = new BinaryReader(file.InputStream))
                    {
                        thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
                    }
                    string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);

                }


    "thePictureDataAsString " variable got Base64 string 


.........................................................................


i am getting file like this in my project

 public ActionResult SaveMake(string inputMakeName, HttpPostedFileBase file)
        {
            MakeModel objMakeModel = new MakeModel();
            if (file.ContentType.Contains("image"))
            {
                string theFileName = Path.GetFileName(file.FileName);
                byte[] thePictureAsBytes = new byte[file.ContentLength];
                using (BinaryReader theReader = new BinaryReader(file.InputStream))
                {
                    thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
                }
                string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
                objMakeModel.ImageBase64 = thePictureDataAsString;
                objMakeModel.Make1 = inputMakeName;
            }

            string response = _apiHelper.ConvertIntoReturnStringPostRequest<MakeModel>(objMakeModel, "api/Transaction/SaveMakes/");
          //  string response = _apiHelper.SaveMake(objMakeModel, "api/Transaction/SaveMakes/");
            return RedirectToAction("AddVehicleMaintenance");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM