ASP.NET Web API 2文件上传 [英] ASP.NET Web API 2 file upload

查看:141
本文介绍了ASP.NET Web API 2文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何最好地使用ASP.NET Web API 2在没有MVC组件的情况下处理文件上载以及添加到要上载的文件中的其他信息.我有Google网,可以告诉您我比预期的更加困惑.

I would like to know how best to handle file upload and addtional information added to the file to be uploaded using ASP.NET Web API 2 without MVC components. I have google the net and I can tell you I am more confused than I expected.

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

The Additional info will be stored in db and the file on the disk. So far the Web API app I am building does not support multipart/form-data. It only supports the default media types. I know I need to create a media formatter.

请帮助.

推荐答案

我写了Javascript split File并上传到WEB API.我认为您可以引用我的后端代码

I had wrote Javascript split File and upload to WEB API . i think you can reference my backend codes

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

In front-end you need using below code to upload your File

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

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

In backend use Request.InputStream.Read to catch your file bytes

    [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文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆