Java.Net.ProtocolException:尝试将文件作为字节流上载时意外结束流

izkcnapc  于 2023-03-04  发布在  .NET
关注(0)|答案(1)|浏览(105)

我有一个图像文件,我试图上传到数据库使用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类型,但我总是得到同样的错误。

ufj5ltwl

ufj5ltwl1#

我通过将httpContent类型更改为MultipartFormDataContent使其工作,因此请求现在看起来如下所示

MultipartFormDataContent content = new MultipartFormDataContent();

                ByteArrayContent fileContent = new ByteArrayContent(file);
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                content.Add(fileContent, "file");
                //ByteArrayContent content = new ByteArrayContent(file);

                httpResponseMessage = await httpClient.PostAsync(uri, content);

这超出了流结束错误。

相关问题