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

1
  • Check this and this. Commented Mar 17, 2018 at 4:55

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't work for me, gives the error System.ArgumentException: 'The format of value '[{"fieldDesc":"ID do Site",.... }]' is invalid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.