2016-12-26 57 views
-1

我想知道如何從給定的文件夾路徑創建新的zip文件,並將其發送回發件人。如何從Web API發送zip文件2 HttpGet

需要的是該文件將在請求它的發件人下載。 我已經看到了很多答案,但沒有幫助我的確切答案。

我的代碼:

的Guid folderGuid = Guid.NewGuid(); string folderToZip = ConfigurationManager.AppSettings [「folderToZip」] + folderGuid.ToString();

Directory.CreateDirectory(folderToZip);

string directoryPath = ConfigurationManager.AppSettings [「DirectoryPath」]; string combinedPath = Path.Combine(directoryPath,id);

DirectoryInfo di = new DirectoryInfo(combinedPath); if(di.Exists) { //提供創建zip文件的路徑和名稱 string zipFile = folderToZip +「\」+ folderGuid +「.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

所以你的問題是關於如何創建壓縮文件或如何發送郵件? – Yoav

+0

如何發送。 –

+0

如果你打算髮送一個zip文件,可能你需要一個POST命令而不是GET,因爲GET的請求大小有限。 – 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

非常感謝! –