• <legend id='AqpFl'><style id='AqpFl'><dir id='AqpFl'><q id='AqpFl'></q></dir></style></legend>

    <i id='AqpFl'><tr id='AqpFl'><dt id='AqpFl'><q id='AqpFl'><span id='AqpFl'><b id='AqpFl'><form id='AqpFl'><ins id='AqpFl'></ins><ul id='AqpFl'></ul><sub id='AqpFl'></sub></form><legend id='AqpFl'></legend><bdo id='AqpFl'><pre id='AqpFl'><center id='AqpFl'></center></pre></bdo></b><th id='AqpFl'></th></span></q></dt></tr></i><div id='AqpFl'><tfoot id='AqpFl'></tfoot><dl id='AqpFl'><fieldset id='AqpFl'></fieldset></dl></div>

      1. <small id='AqpFl'></small><noframes id='AqpFl'>

          <bdo id='AqpFl'></bdo><ul id='AqpFl'></ul>

      2. <tfoot id='AqpFl'></tfoot>

        使用HttpClient分块上传大文件到Controller,IFormFile总是为空

        时间:2023-07-11
          <tbody id='O2T7C'></tbody>

            <bdo id='O2T7C'></bdo><ul id='O2T7C'></ul>
            <tfoot id='O2T7C'></tfoot>

          • <small id='O2T7C'></small><noframes id='O2T7C'>

                  <legend id='O2T7C'><style id='O2T7C'><dir id='O2T7C'><q id='O2T7C'></q></dir></style></legend>
                1. <i id='O2T7C'><tr id='O2T7C'><dt id='O2T7C'><q id='O2T7C'><span id='O2T7C'><b id='O2T7C'><form id='O2T7C'><ins id='O2T7C'></ins><ul id='O2T7C'></ul><sub id='O2T7C'></sub></form><legend id='O2T7C'></legend><bdo id='O2T7C'><pre id='O2T7C'><center id='O2T7C'></center></pre></bdo></b><th id='O2T7C'></th></span></q></dt></tr></i><div id='O2T7C'><tfoot id='O2T7C'></tfoot><dl id='O2T7C'><fieldset id='O2T7C'></fieldset></dl></div>
                  本文介绍了使用HttpClient分块上传大文件到Controller,IFormFile总是为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我正在尝试创建一个 .Net 标准客户端"类,用于将(有时非常大)文件上传到控制器.我想通过将文件分成块并一次上传一个来做到这一点.目的是让其他应用程序使用它,而不是直接与 Web Api 通信.

                  I am trying to create a .Net Standard "Client" class for uploading (sometimes very large) files to a Controller. I want to do this by breaking the file into chunks and uploading them one at a time. The intent is for other applications to use this instead of communicating directly to the Web Api.

                  我已经让控制器工作了.我已经验证它可以使用支持块保存的 Kendo-ui 控件工作.

                  I already have the Controller working. I've verified that it works using a Kendo-ui control which supports chunk-saving.

                  我遇到的问题是 IEnumerable<IFormFile>从我的客户端类发布时,我的控制器的文件参数始终为空

                  The issue I am having is that the IEnumerable<IFormFile> files parameter for my controller is always empty when posted from my client class

                  控制器

                  [Route("api/Upload")]
                  public ActionResult ChunkSave(IEnumerable<IFormFile> files, string metaData, Guid id)
                  {
                      MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(metaData));
                      var serializer = new DataContractJsonSerializer(typeof(ChunkMetaData));
                      ChunkMetaData somemetaData = serializer.ReadObject(ms) as ChunkMetaData;
                  
                      // The Name of the Upload component is "files"
                      if (files != null)
                      {
                          // If this is the first chunk, try to delete the file so that we don't accidently
                          // and up appending new bytes to the old file.
                          if (somemetaData.ChunkIndex == 0)
                          {
                              _io.DeleteFile(id, Path.GetFileName(somemetaData.FileName));
                          }
                  
                          foreach (var file in files)
                          {
                              // Some browsers send file names with full path. This needs to be stripped.
                               _io.AppendToFile(id, Path.GetFileName(somemetaData.FileName), file.OpenReadStream());
                          }
                      }
                  
                      FileResult fileBlob = new FileResult();
                      fileBlob.uploaded = somemetaData.TotalChunks - 1 <= somemetaData.ChunkIndex;
                      fileBlob.fileUid = somemetaData.UploadUid;
                      return new JsonResult(fileBlob);
                  }
                  

                  客户:

                  public class FileTransferClient
                  {
                      HttpClient Client { get; set; } 
                  
                      public FileTransferClient(Uri apiUrl)
                      {
                          this.Client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true })
                          {
                              BaseAddress = apiUrl
                          };
                          this.Client.DefaultRequestHeaders.Accept.Add(
                              new MediaTypeWithQualityHeaderValue("application/json"));
                      }
                  
                      public async Task<bool> UploadFile(Guid id, Stream file, string name, string contentType)
                      {
                          bool ret = true;
                          int chunckSize = 2097152; //2MB
                          int totalChunks = (int)(file.Length / chunckSize);
                          if (file.Length % chunckSize != 0)
                          {
                              totalChunks++;
                          }
                  
                          for (int i = 0; i < totalChunks; i++)
                          {
                              long position = (i * (long)chunckSize);
                              int toRead = (int)Math.Min(file.Length - position + 1, chunckSize);
                              byte[] buffer = new byte[toRead];
                              await file.ReadAsync(buffer, 0, toRead);
                  
                              MultipartFormDataContent content = new MultipartFormDataContent();
                              content.Add(new StringContent(id.ToString()), "id");
                              var meta = JsonConvert.SerializeObject(new ChunkMetaData
                              {
                                  UploadUid = id.ToString(),
                                  FileName = name,
                                  ChunkIndex = i,
                                  TotalChunks = totalChunks,
                                  TotalFileSize = file.Length,
                                  ContentType = contentType
                              });
                              content.Add(new StringContent(meta), "metaData");
                              using (var ms = new MemoryStream(buffer))
                              {
                                  content.Add(new StreamContent(ms),"files");
                                  var response = await Client.PostAsync("/api/Upload", content).ConfigureAwait(false);
                                  if (!response.IsSuccessStatusCode)
                                  {
                                      ret = false;
                                      break;
                                  }
                              }
                          }
                          return ret;
                      }
                  }
                  

                  推荐答案

                  问题是我使用 StreamContent 而不是 ByteArrayContent 来表示我的文件块.这是我最终得到的结果:

                  The issue was that I was using a StreamContent instead of a ByteArrayContent to represent my file chunks. Here's what I ended up with:

                  public async Task<Bool> UploadFileAsync(Guid id, string name, Stream file)
                  {
                      int chunckSize = 2097152; //2MB
                      int totalChunks = (int)(file.Length / chunckSize);
                      if (file.Length % chunckSize != 0)
                      {
                          totalChunks++;
                      }
                  
                      for (int i = 0; i < totalChunks; i++)
                      {
                          long position = (i * (long)chunckSize);
                          int toRead = (int)Math.Min(file.Length - position + 1, chunckSize);
                          byte[] buffer = new byte[toRead];
                          await file.ReadAsync(buffer, 0, buffer.Length);
                  
                          using (MultipartFormDataContent form = new MultipartFormDataContent())
                          {
                              form.Add(new ByteArrayContent(buffer), "files", name);
                              form.Add(new StringContent(id.ToString()), "id");
                              var meta = JsonConvert.SerializeObject(new ChunkMetaData
                              {
                                  UploadUid = id.ToString(),
                                  FileName = name,
                                  ChunkIndex = i,
                                  TotalChunks = totalChunks,
                                  TotalFileSize = file.Length,
                                  ContentType = "application/unknown"
                              });
                              form.Add(new StringContent(meta), "metaData");
                              var response = await Client.PostAsync("/api/Upload", form).ConfigureAwait(false);
                              return response.IsSuccessStatusCode;
                          }
                      }
                      return true;
                  }
                  

                  这篇关于使用HttpClient分块上传大文件到Controller,IFormFile总是为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:在两个 ASP.NET Core 应用程序之间共享 Cookie 下一篇:ASP.NET 5/MVC 6 控制台托管应用程序

                  相关文章

                  1. <legend id='GvL6r'><style id='GvL6r'><dir id='GvL6r'><q id='GvL6r'></q></dir></style></legend>

                    <small id='GvL6r'></small><noframes id='GvL6r'>

                      <i id='GvL6r'><tr id='GvL6r'><dt id='GvL6r'><q id='GvL6r'><span id='GvL6r'><b id='GvL6r'><form id='GvL6r'><ins id='GvL6r'></ins><ul id='GvL6r'></ul><sub id='GvL6r'></sub></form><legend id='GvL6r'></legend><bdo id='GvL6r'><pre id='GvL6r'><center id='GvL6r'></center></pre></bdo></b><th id='GvL6r'></th></span></q></dt></tr></i><div id='GvL6r'><tfoot id='GvL6r'></tfoot><dl id='GvL6r'><fieldset id='GvL6r'></fieldset></dl></div>
                        <bdo id='GvL6r'></bdo><ul id='GvL6r'></ul>
                    1. <tfoot id='GvL6r'></tfoot>