Опубликовать файл размером более 64 КБ в WebApi - PullRequest
0 голосов
/ 26 октября 2018

Я использую Postman для отправки двоичного файла размером более 64 КБ в контроллер WebApi.

При чтении потока я получаю первые 64 КБ данных, и все, что больше, заполнено пустыми байтами.

Не могу понять, что я пропустил.

Редактировать: Также я пробовал IIS и IIS Express.

Config

<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="DocumentService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxRequestLength="2097152" />
  </system.web>

  <system.webServer>
    <modules>
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <remove name="WebDAV" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
    </security>
  </system.webServer>
  <applicationSettings>
    <DocumentService.Properties.Settings>
      <setting name="datafolder" serializeAs="String">
        <value>c:\temp\</value>
      </setting>
    </DocumentService.Properties.Settings>
  </applicationSettings>
</configuration>

код

[Route("api/documents/{company}/{type}/{id}")]
public async Task<IHttpActionResult> Post(string company, string type, string id)
{

    string path = System.IO.Path.Combine(Properties.Settings.Default.datafolder, company, type, id);
    if (System.IO.File.Exists(path))
    {
        return BadRequest($"File {path} already exists");
    }

    var data = Request.Content.ReadAsStreamAsync().Result;
    data.Position = 0;
    var buffer = new Byte[data.Length];
    // <-- data.length corresponds with the length of the file. 
    //     the first 64KB are filled with data the rest are empty bytes
    await data.ReadAsync(buffer, 0, (int)data.Length);
    System.IO.File.WriteAllBytes(path, buffer);

    return Ok();
}

1 Ответ

0 голосов
/ 29 октября 2018

@ kaarthickraman помог мне выбрать правильный путь.

Я тестировал Postman, используя опцию binary вместо опции form-data. Это работает! Хотя я до сих пор не понимаю, почему бинарный параметр не работает.

Также изменение кода:

[Route("api/documents/{company}/{type}/{id}")]
public async Task<IHttpActionResult> Post(string company, string type, string id)
{

    string path = System.IO.Path.Combine(Properties.Settings.Default.datafolder, company, type, id);
    if (System.IO.File.Exists(path))
    {
            return BadRequest($"File {path} already exists");
    }

    HttpRequest req = HttpContext.Current.Request;
    if (req.Files.Count != 1)
    {
        return BadRequest();
    }

    HttpPostedFile file = req.Files[0];
    byte[] buffer = new Byte[file.InputStream.Length];
    await file.InputStream.ReadAsync(buffer, 0, (int)file.InputStream.Length);
    File.WriteAllBytes(path, buffer);

    return Ok();
}

postman

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...