简体   繁体   English

同时将JSON数据和图像发布到Web API 2

[英]Post JSON data and image at the same time to a web API 2

I have a function which adds data to a SQL Database and upload an image(s) to the server. 我有一个将数据添加到SQL数据库并将图像上传到服务器的功能。

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. 我将图像转换为base64字符串以与我的帖子一起发送,但我看到图像大小比原始文件大33%。 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 我正在通过邮递员或JQuery测试Web API

Try using Mulitpart/Fromdata post. 尝试使用Mulitpart / Fromdata帖子。 Using this you can send files and your JSON Data at the same time. 使用此功能,您可以同时发送文件和JSON数据。 However you need to change you API to read multipartformdata. 但是,您需要更改API才能读取multipartformdata。 This way file size will be less as compared to base64string. 这样,文件大小将比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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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