POST StreamContent与多个文件

时间:2015-10-16 13:26:33

标签: c# json post asp.net-web-api

下面的代码片段成功将单个文件HttpPost到WebAPI。我想扩展它以构建包含多个文件的StreamContent(类似于Fiddler多文件帖子)。

我知道我应该为StreamContent添加一个“边界”,但我不确定究竟在哪里。我想最终将FileStream / Stream参数转换为List,这样我就可以遍历集合并将StreamContent构建为POST。

如果这篇文章有任何意义,请告诉我。我很感激任何建议。

提前致谢!

public async Task<HttpStatusCode> UploadOrderFile(FileStream imageFileStream, string filename, string contentType = "image/png")
    {
        JsonApiClient._client.DefaultRequestHeaders.Clear();
        var content = new MultipartFormDataContent
        {
            JsonApiClient.CreateFileContent(imageFileStream, filename, contentType)
        };
        JsonApiClient._client.DefaultRequestHeaders.Add("Authorization",
            " Bearer " + JsonApiClient.Token.AccessToken);
        var response = await JsonApiClient._client.PostAsync("api/UploadFile", content);

        response.EnsureSuccessStatusCode();
        return response.StatusCode;
    }

internal static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
    {
        var fileContent = new StreamContent(stream);
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "\"files\"",
            FileName = "\"" + fileName + "\""
        }; 
        fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return fileContent;
    }

编辑:我在接收和保存已发布文件时没有任何问题。问题在于创建发布多个文件所需的StreamContent。

2 个答案:

答案 0 :(得分:3)

这是我尝试过的适用于我的解决方案。 CreateFileContent中没有更改任何内容。我只是简单地将参数转换为集合,遍历每个集合,并从多个StreamContent中添加新的MultiPartFormDataContent。边界也被添加到MultipartFormDataContent对象中。如果您发现任何效率低下或完全错误的事情,请告诉我。谢谢!

public async Task<HttpStatusCode> UploadOrderFile(List<FileStream> imageFileStream, List<string> filename, string salesOrderNo, List<string> contentType)
    {
        JsonApiClient._client.DefaultRequestHeaders.Clear();
        var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
        var content = new MultipartFormDataContent(boundary); 
        for (var i = 0; i < imageFileStream.Count; i++)
        {
            content.Add(JsonApiClient.CreateFileContent(imageFileStream[i], filename[i], contentType[i]));
        }

        JsonApiClient._client.DefaultRequestHeaders.Add("Authorization",
            " Bearer " + JsonApiClient.Token.AccessToken);
        var response = await JsonApiClient._client.PostAsync("api/UploadFile", content);

        response.EnsureSuccessStatusCode();
        return response.StatusCode;
    }

internal static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
    var fileContent = new StreamContent(stream);
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
    {
        Name = "\"files\"",
        FileName = "\"" + fileName + "\""
    }; 
    fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
    return fileContent;
}

答案 1 :(得分:1)

尝试这种方法

     public HttpResponseMessage Post()
        {
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                foreach(string file in httpRequest.Files)
                {                   
 var content = new MultipartFormDataContent
        {
            JsonApiClient.CreateFileContent(postedFile.InputStream, postedFile.FileName, postedFile.ContentType)
        };
                 // NOTE: To store in memory use postedFile.InputStream
                }

                return Request.CreateResponse(HttpStatusCode.Created);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }


    internal static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
        {
            var fileContent = new StreamContent(stream);
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "\"files\"",
                FileName = "\"" + fileName + "\""
            }; 
            fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            return fileContent;
        }