我有一个图像文件,我试图上传到数据库使用http API。每次我尝试上传我得到相同的错误:
[monodroid] Not wrapping exception of type Java.Net.ProtocolException from method `Read`. This will change in a future release.
unexpected end of stream
下面是我的代码
using GT_MI.API;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Newtonsoft.Json;
namespace ShorelogApp.API.Misc
{
public class SaveSeas : ApiBase<RequestBase, SaveSeas.Response>
{
public class Response : ResponseBase
{
public string Path { get; set; }
public string FileName { get; set; }
}
/// <summary>
///
/// </summary>
/// <param name="file">Byte array representing binary encoded file</param>
/// <returns></returns>
public async Task<Response> SaveFileAsync(byte[] file)
{
HttpResponseMessage httpResponseMessage = null;
try
{
// Construct the HttpClient and Uri, with a timeout of 16 seconds
var httpClient = new HttpClient()
{
Timeout = TimeSpan.FromSeconds(16)
};
var uri = new Uri($"{ApiManager.BaseUrl}/seas/save_seas");
Debug.WriteLine($"URL: {uri.AbsoluteUri}");
if (string.IsNullOrEmpty(ApiManager.Token) == false)
{
Debug.WriteLine($"[Token]: {ApiManager.Token}");
httpClient.DefaultRequestHeaders.Add("token", ApiManager.Token);
}
// using byte array content type
ByteArrayContent content = new ByteArrayContent(file);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); //"application/octet-stream"
content.Headers.ContentLength = file.Length;
httpResponseMessage = await httpClient.PostAsync(uri, content);
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Debug.WriteLine($"Response Data: {httpResponseBody}");
var resultJson = JsonConvert.DeserializeObject<Response>(httpResponseBody, jsonSerializerSettings);
Debug.WriteLine($"Response Json:\n{JsonConvert.SerializeObject(resultJson, Formatting.Indented)}");
return resultJson;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return HandleException(httpResponseMessage, ex);
}
}
}
}
我试过添加一个包含文件大小的内容头,因为我读到有时候这个错误是由于请求主体在后端被识别为错误的大小而引起的,但是它不起作用。我试过在上传之前压缩文件,因为我想它可能太大了,但是那不起作用。我试过通过JSON上传文件作为一个字符串,然后上传它作为一个ByteArrayContent类型,但我总是得到同样的错误。
1条答案
按热度按时间ufj5ltwl1#
我通过将httpContent类型更改为MultipartFormDataContent使其工作,因此请求现在看起来如下所示
这超出了流结束错误。