Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API 2 file upload

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.

like image 797
Arsene Avatar asked Apr 03 '14 10:04

Arsene


People also ask

How do you send a file using multipart form data?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.


1 Answers

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

         };
    }
like image 183
King Jk Avatar answered Sep 22 '22 18:09

King Jk