ASP.NET Web API 2 文件上传

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

我想知道如何最好地处理文件上传和添加到要使用 ASP.NET Web API 2 上传的文件的附加信息,而无需 MVC 组件。我在网上谷歌了一下,我可以告诉你我比我预期的更困惑。

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

请帮忙。

最佳答案

我写了 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)
        {

         };
    }

关于ASP.NET Web API 2 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835246/

相关文章:

c# - ASP.net 在 Html.DisplayFor 之后添加文本

c# - 路由请求时 HttpContext.Current.Session 为 null

javascript - 获取 javascript 动态创建的控件状态

c# - Entity Framework 6 - ASP.NET 过滤器 - 并发添加

asp.net-web-api2 - 将未经授权的请求重定向到 Azure AD 进行登录

c# - 在控制台应用程序中添加对 System.Web.Http 的引用

jquery - dropdownlist 的 selectedindexchanged 事件不适用于 jquery

asp.net - 如何在 Windows 10 上注册 ASP.NET?

c# - Controller 要求在进入时下载

c# - 目标机主动拒绝导致无法连接?