如何将zip文件发送到ASP.NET WebApi
我想知道如何将zip文件发送到WebApi控制器,反之亦然。 问题是我的WebApi使用json传输数据。 zip文件不可序列化,也可以是流。 字符串可以序列化。 但是必须有另一种解决方案,而不是将zip转换为字符串而不是发送字符串。 这听起来不对。
知道怎么做的吗?
如果您的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 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表单时,这对我enctype="multipart/form-data"
。
尝试使用简单的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 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 (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; }