Post JSON 数据和图片同时上传到一个网站 API 2
Post JSON data and image at the same time to a web API 2
我有一个功能可以将数据添加到 SQL 数据库并将图像上传到服务器。
我将图像转换为 base64 字符串以便与 post 一起发送,但我发现图像大小比原始文件大 33%。我想更改它,但我不知道如何更改。
这是我的代码:
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);
}
我正在通过 Postman 或 JQuery
测试网络 api
尝试使用 Mulitpart/Fromdata post。使用此功能,您可以同时发送文件和 JSON 数据。但是,您需要更改 API 以读取 multipartformdata。与 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;
我有一个功能可以将数据添加到 SQL 数据库并将图像上传到服务器。
我将图像转换为 base64 字符串以便与 post 一起发送,但我发现图像大小比原始文件大 33%。我想更改它,但我不知道如何更改。
这是我的代码:
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);
}
我正在通过 Postman 或 JQuery
测试网络 api尝试使用 Mulitpart/Fromdata post。使用此功能,您可以同时发送文件和 JSON 数据。但是,您需要更改 API 以读取 multipartformdata。与 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;