【问题标题】:ASP.NET Web API 2 file uploadASP.NET Web API 2 文件上传
【发布时间】:2014-05-15 03:22:42
【问题描述】:

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

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

请帮忙。

【问题讨论】:

标签: asp.net asp.net-web-api2


【解决方案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);

在后端使用 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)
        {

         };
    }

【讨论】:

    【解决方案2】:

    您可以将文件数据序列化为 BASE64 并将它们作为字符串发送,以防由于某种原因不允许使用 multipart/from-data。

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 2012-07-27
      相关资源
      最近更新 更多