Upload files via web api, the files are sent as byte[]

Viewed 193

I'm trying to upload files via web api, the files are sent as byte[].

I manage to upload only one file per request, but if I select multiple files it only upload one file.

This is the client side code:

var content = new MultipartFormDataContent();
ByteArrayContent byteContent = new ByteArrayContent(_mediaFile);
content.Add(byteContent, "file", _mediaFIleName);
var httpClient = new HttpClient();
var uploadServiceBaseAddress = "http://localhost:1000/api/home/Upload";
var httpResponseMessage = httpClient.PostAsync(uploadServiceBaseAddress, content);

This is the server side code:

var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
     var postedFile = httpRequest.Files[file];
     var filePath = HttpContext.Current.Server.MapPath("~/uploads" + postedFile.FileName);
     postedFile.SaveAs(filePath);
}

Is there another method to do this or am I doing something wrong here in the code above?

1 Answers

see this example

[HttpGet]
public IHttpActionResult SendBytes(string input)
{
    string[] paths = input.Split('*');
           
    foreach (var path in paths)
    {
       var content = new MultipartFormDataContent();
       ByteArrayContent byteContent = new ByteArrayContent(File.ReadAllBytes(path));
       content.Add(byteContent, "file", path);
       var httpClient = new HttpClient();
       var uploadServiceBaseAddress = "http://localhost:56381/api/BazarAlborzApp/RecieveBytes";
       var httpResponseMessage = httpClient.PostAsync(uploadServiceBaseAddress, content);
    }
    return Ok<int>(0);
}

[HttpPost]
public IHttpActionResult RecieveBytes()
{       
    var httpRequest = HttpContext.Current.Request;
    foreach (string file in httpRequest.Files)
    {
        var postedFile = httpRequest.Files[file];
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("/uploads/" + postedFile.FileName));
        postedFile.SaveAs(filePath);
    }
    return Ok<int>(0);
}
Related