ASP.NET Web API 2 file upload

南楼画角 提交于 2019-12-08 14:53:53

问题


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.

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.

Pls help.


回答1:


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);

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)
        {

         };
    }



回答2:


You can just serialize your file data into BASE64 and send them as a string in case of multipart/from-data is not allowed for some reason.



来源:https://stackoverflow.com/questions/22835246/asp-net-web-api-2-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!