0

I have a function which adds data to a SQL Database and upload an image(s) to the server.

I convert the image into base64 string to send it with my post but I read that the image size is 33% bigger than the original file. I would like to change that but I don't how.

This is my code:

public async Task<IHttpActionResult> Post([FromBody]Post userpost)
    {
        if (ModelState.IsValid)
       {
            int postid = Convert.ToInt32(postDB.AddPost(userpost));                   

            if (userpost.fileBody.Length > 0)
            {
                var filename = string.Format("{0}_{1}{2}", postid, Guid.NewGuid().ToString(), ".jpg");

                var ms = new MemoryStream(Convert.FromBase64String(userpost.fileBody));

                 await upload.UploadFile(filename, ms, "image/jpg","images");

                ms.Close();

                return Content(HttpStatusCode.Accepted, "{\"pic\":\"" + filename + "\"}");
            }
            else
                return Ok(HttpStatusCode.OK);
        }
        else
            return Ok(HttpStatusCode.NotAcceptable);
    }

I'm test the web api by Postman or JQuery

Daina Hodges
  • 823
  • 3
  • 12
  • 37
  • Check [this](https://stackoverflow.com/a/12903157/5740031) and [this](https://stackoverflow.com/a/19728580/5740031). – CodeFuller Mar 17 '18 at 04:55

1 Answers1

1

Try using Mulitpart/Fromdata post. Using this you can send files and your JSON Data at the same time. However you need to change you API to read multipartformdata. This way file size will be less as compared to base64string.

      var jsonToSend = JsonConvert.SerializeObject(json, Formatting.None);
  var multipart = new MultipartFormDataContent();
  var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");
  multipart.Add(body, "JsonDetails");
  multipart.Add(new ByteArrayContent(System.IO.File.ReadAllBytes("E:\\file.png")), "DocumentDetails", "file1.png");
  var httpClient = new HttpClient();
  httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
  var response = httpClient.PostAsync(new Uri("uriToPost"), multipart).Result;
sudhir
  • 46
  • 1
  • Didn't work for me, gives the error ```System.ArgumentException: 'The format of value '[{"fieldDesc":"ID do Site",.... }]' is invalid.``` – Renan Ribeiro Jun 01 '23 at 13:33