2016-12-26 8 views
-1

私は、特定のフォルダパスから新しいzipファイルを作成し、送信者に送り返す方法を理解しようとしています。Web API 2からzipファイルを送信する方法HttpGet

ファイルを要求した送信者がファイルをダウンロードする必要があります。 私は多くの答えを見たことがありますが、誰も正確な答えで私を助けませんでした。

マイコード:

のGUID folderGuid = Guid.NewGuid()。 string folderToZip = ConfigurationManager.AppSettings ["folderToZip"] + folderGuid.ToString();

Directory.CreateDirectory(folderToZip);

string directoryPath = ConfigurationManager.AppSettings ["DirectoryPath"]; 文字列combinedPath = Path.Combine(directoryPath、id);

DirectoryInfo di =新しいDirectoryInfo(combinedPath); (di.Exists) {//は ストリングzipファイル= folderToZip + "\" + folderGuid + ".zipファイル" を作成するZIPファイルのパスおよび名前を提供する場合。お使いのコントローラで

//call the ZipFile.CreateFromDirectory() method 
ZipFile.CreateFromDirectory(combinedPath, zipFile, CompressionLevel.Fastest, true); 

var result = new HttpResponseMessage(HttpStatusCode.OK); 
using (ZipArchive zip = ZipFile.Open(zipFile, ZipArchiveMode.Read)) 
{ 
    zip.CreateEntryFromFile(folderFiles, "file.zip"); 
} 

var stream = new FileStream(zipFile, 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" 
}; 
log.Debug("END ExportFiles()"); 
return ResponseMessage(result); 
+2

だからあなたの質問は、zipファイルを作成するか、どのようにそれを送信する方法についてです存在? – Yoav

+0

送信方法。 –

+0

zipファイルを送信する場合、GETにはリクエストサイズが限られているため、おそらくPOSTコマンドが必要です。 – GeorgeT

答えて

0

using System.IO.Compression.FileSystem; // Reference System.IO.Compression.FileSystem.dll 

[HttpGet] 
[Route("api/myzipfile"] 
public dynamic DownloadZip([FromUri]string dirPath) 
{ 
if(!System.IO.Directory.Exists(dirPath)) 
    return this.NotFound(); 

    var tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid()); // might want to clean this up if there are a lot of downloads 
    ZipFile.CreateFromDirectory(dirPath, tempFile); 
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 
    response.Content = new StreamContent(new FileStream(tempFile, FileMode.Open, FileAccess.Read)); 
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
    response.Content.Headers.ContentDisposition.FileName = fileName; 
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); 

    return response; 
} 

UPD:回避策ファイルが既に

+0

例外 'C:\ **** \ **** \ AppData \ Local \ Temp \ tmp96C2.tmpファイルを例外がスローされます' もう存在している。 –

+0

@ o.Nassieコードを修正しました。 – zaitsman

+0

ありがとうございます! –

関連する問題