【问题标题】:Keep on getting the same error when I try to upload an image on Xamarin Forms当我尝试在 Xamarin Forms 上上传图像时,继续收到相同的错误
【发布时间】:2021-11-17 22:51:53
【问题描述】:

我正在尝试在 Xamarin 表单上上传图像,但我不断收到错误消息:发送请求时发生错误。我用于上传的代码是:

try
{
    var content = new MultipartFormDataContent();

    content.Add(new StreamContent(_mediaFile.GetStream()), "\"file\"", $"\"{_mediaFile.Path}\"");

    var uploadUrl = "{url}/api/files/upload";

    var httpClient = new HttpClient();                               

    var httpResponseMessage = await httpClient.PostAsync(uploadUrl, content);

    System.Net.ServicePointManager.SecurityProtocol =
        SecurityProtocolType.Tls12 |
        SecurityProtocolType.Tls11 |
        SecurityProtocolType.Tls;

    var response = httpResponseMessage.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
} 

服务器上的代码如下所示:

[Route("api/files/upload")]
[HttpPost]
public async Task<string> Post()
{
    try
    {
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var fileName = postedFile.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
                var filePath = HttpContext.Current.Server.MapPath("~/Uploads/" + fileName);
                postedFile.SaveAs(filePath);
                return "/Uploads/" + fileName;
            }
        }
    }
    catch (Exception exception)
    {
        return exception.Message;
    }

    return "no files";

}

但是,在上传时,甚至在到达服务器之前,我收到了错误:发送请求时发生错误。任何人都可以帮助我,我已经搜索了整个错误但没有人真正解决了这个错误。有人可以帮助我吗?

【问题讨论】:

  • 您需要查看异常对象并获取异常的详细信息,尤其是InnerException 属性
  • 您在哪里运行您的应用程序?安卓? IOS?乌普? Android 可能需要互联网访问权限。 iOS 的 httpClient 可以从项目设置中更改。在发送请求之前尝试更改 tls 设置
  • 嗨@JuanSturla,我正在运行Android 版本,但错误不断出现。让我尝试按照您的建议更改 TLS 设置...但是我该怎么做呢?
  • 嗨@Jason.. 让我检查一下并回复你
  • 上传图片最好以base64格式上传。通过这种方式,您将其作为字符串发送。试试这个,而不是使用 MultiFormDataContent

标签: c# xamarin.forms file-upload httprequest


【解决方案1】:

我认为问题在于图像大小 尝试上传小于 2 MB 的图片 如果可行,请将此代码放在服务器的 web.config 文件中以下载更大的图像

 <system.web>
  
    <httpRuntime targetFramework="4.8" maxRequestLength="2147483647" />
     
  </system.web>
  <system.webServer>
      <security>
          <requestFiltering>
              <requestLimits maxAllowedContentLength="100000000"></requestLimits>
          </requestFiltering>
      </security>
</system.webServer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 2021-03-13
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2017-04-19
    • 2020-12-16
    • 1970-01-01
    相关资源
    最近更新 更多