如何将zip文件发送到ASP.NET WebApi

时间:2014-03-04 15:30:06

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

我想知道如何将zip文件发送到WebApi控制器,反之亦然。 问题是我的WebApi使用json传输数据。 zip文件不可序列化,也可以是流。字符串可以序列化。但是必须有另一种解决方案,而不是将zip转换为字符串而不是发送字符串。这听起来不对。

知道如何做到这一点?

2 个答案:

答案 0 :(得分:5)

如果您的API方法需要HttpRequestMessage,那么您可以从中获取流:

public HttpResponseMessage Put(HttpRequestMessage request)
{
    var stream = GetStreamFromUploadedFile(request);

    // do something with the stream, then return something
}

private static Stream GetStreamFromUploadedFile(HttpRequestMessage request)
{
    // Awaiting these tasks in the usual manner was deadlocking the thread for some reason.
    // So for now we're invoking a Task and explicitly creating a new thread.
    // See here: http://stackoverflow.com/q/15201255/328193
    IEnumerable<HttpContent> parts = null;
    Task.Factory
        .StartNew(() => parts = request.Content.ReadAsMultipartAsync().Result.Contents,
                        CancellationToken.None,
                        TaskCreationOptions.LongRunning,
                        TaskScheduler.Default)
        .Wait();

    Stream stream = null;
    Task.Factory
        .StartNew(() => stream = parts.First().ReadAsStreamAsync().Result,
                        CancellationToken.None,
                        TaskCreationOptions.LongRunning,
                        TaskScheduler.Default)
        .Wait();
    return stream;
}

当发布带有enctype="multipart/form-data"的HTTP表单时,这对我有用。

答案 1 :(得分:4)

尝试使用简单的HttpResponseMessage,其中包含一个StreamContent到GET,下载文件

public HttpResponseMessage Get()
{
    var path = @"C:\Temp\file.zip";
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                            {
                                FileName = "file.zip"
                            };
    return result;
}

和POST,上传文件

public Task<HttpResponseMessage> Post()
{
    HttpRequestMessage request = this.Request;
    if (!request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }


    var provider = new MultipartFormDataStreamProvider("C:\Temp");

    var task = request.Content.ReadAsMultipartAsync(provider).
        ContinueWith<HttpResponseMessage>(o =>
        {

            string file1 = provider.BodyPartFileNames.First().Value;
            // this is the file name on the server where the file was saved 

            return new HttpResponseMessage()
            {
                Content = new StringContent("File uploaded.")
            };
        }
    );
    return task;
}