HttpClient: How to upload multiple files at once

前端 未结 1 483
你的背包
你的背包 2020-12-13 19:43

I am trying to upload muliple files using System.Net.Http.HttpClient.

using (var content = new MultipartFormDataContent())
{
   content.Add(new StreamContent         


        
相关标签:
1条回答
  • 2020-12-13 20:13

    Nailed it. But behaviour is strange.

    using (var content = new MultipartFormDataContent())
    {
        content.Add(CreateFileContent(imageStream, "image.jpg", "image/jpeg"));
        content.Add(CreateFileContent(signatureStream, "image.jpg.sig", "application/octet-stream"));
    
        var response = await httpClient.PostAsync(_profileImageUploadUri, content);
        response.EnsureSuccessStatusCode();
    }
    
    private StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
    {
        var fileContent = new StreamContent(stream);
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") 
        { 
            Name = "\"files\"", 
            FileName = "\"" + fileName + "\""
        }; // the extra quotes are key here
        fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);            
        return fileContent;
    }
    
    [HttpPost]
    public ActionResult UploadProfileImage(IList<HttpPostedFileBase> files)
    {
        if(files == null || files.Count != 2)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    
        // more code
    }
    
    0 讨论(0)
提交回复
热议问题