ASP.NET Web API 2文件上载

Ars*_*ene 14 asp.net asp.net-web-api2

我想知道如何最好地处理文件上传和添加到要使用没有MVC组件的ASP.NET Web API 2上载的文件的附加信息.我有谷歌网,我可以告诉你我比我想象的更困惑.

附加信息将存储在db中,文件存储在磁盘上.到目前为止,我正在构建的Web API应用程序不支持multipart/form-data.它仅支持默认媒体类型.我知道我需要创建一个媒体格式化程序.

请帮忙.

Kin*_* Jk 1

我编写了 Javascript split File 并上传到 WEB API 。我想你可以参考我的后端代码

在前端,您需要使用以下代码来上传文件

  var xhr = new self.XMLHttpRequest();
  xhr.open('POST', url, false);
  xhr.setRequestHeader('Content-Type', 'application/octet-stream');
  xhr.send(chunk);
Run Code Online (Sandbox Code Playgroud)

在后端使用 Request.InputStream.Read 来捕获文件字节

    [HttpPost]
    [ValidateInput(false)]
    public string fileUpload(string filename)
    {
        byte[] file = new byte[Request.InputStream.Length];
        Request.InputStream.Read(file, 0, Convert.ToInt32(Request.InputStream.Length));
        BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
        binWriter.Write(file);
        StreamReader reader = new StreamReader(binWriter.BaseStream);
        reader.BaseStream.Position = 0;
        //This example is recevied text file
        while ((line = reader.ReadLine()) != null)
        {

         };
    }
Run Code Online (Sandbox Code Playgroud)