通过 web api 上传文件,文件以 byte[] 形式发送

问题描述

我正在尝试通过 web api 上传文件文件以 byte[] 的形式发送。

我设法每个请求只上传一个文件,但如果我选择多个文件,它只能上传一个文件

这是客户端代码

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

这是服务器端代码

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

是否有其他方法可以做到这一点,或者我在上面的代码中做错了什么?

解决方法

看这个例子

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