I have a service called DownloadZipFile that collates data and then builds a Zip file for it to be downloaded. this service returns a response containing the stream to the file
Service:
[HttpPost]
public ActionResult DownloadZipFile(string zipData)
{
try
{
// Create the Zip File.
using (MemoryStream zipStream = DownloadHelper.BuildZipFileData(zipData))
{
// Build up the reponse including the file.
HttpContext.Response.ClearContent();
HttpContext.Response.ClearHeaders();
HttpContext.Response.Clear();
HttpContext.Response.Buffer = true;
HttpContext.Response.ContentType = "application/zip";
HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=MyZipFile.zip;");
HttpContext.Response.BinaryWrite(zipStream.ToArray());
HttpContext.Response.End();
}
}
catch (Exception e)
{
// Log the error.
_logService.Error(LogHelper.GetWebRequestInfo(ControllerContext.HttpContext.Request), e);
}
}
It would download and open the zip file correctly if I call the service like this.
Service Call #1
var form = $("<form></form>").attr('action', "DownloadZipFile").attr("method", "post");
form.append($("<input></input>").attr("type", "hidden").attr("name", "zipData").attr('value', escape(JSON.stringify(zipData))));
form.appendTo('body').submit().remove();
However, if I use an AJAX Post call when converting it from response to blob, the size is much larger than what I sent.
Service Call #2:
$.post("DownloadZipFile", { zipData: escape(JSON.stringify(zipData)) },
function (data, status, response) {
var filename = "";
var disposition = response.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = response.getResponseHeader('Content-Type');
var blob = new Blob([data], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
}
});
Using Service Call #2 the Zip File I get is corrupted
Could it be the encoding? I checked the data between the correct and incorrect Zip Files and they look like this:
Correct Zip:
PK ú‚ÐJmÇ´¸g € BOM.csvu‘ËNÃ0E÷HüÃÈ+ÆÑØy/›”WÔðH[Ä64IÕ¦|>‰_ÀN(-¢l®,Ýã;wìÏ÷‡m^Ö³ú 35VkUŽtÕf6)óºZcZjqz"0dÒ³ü9TÓ%yd#ˆ3Ö˜R›¡kÙMYæt2'Òâ¦É½dÈhO¶"BXÁ?ùÚ”Ç<‰,ÖÍ ‘ååÎé ÁÝ!Ò ²AˆVG ]3
Corrupted Zip:
PK ￿￿￿g ￿ BOM.csvu￿￿￿E￿￿+￿￿/￿￿W￿H[￿4Iզ|>￿_￿(-￿l￿,￿;w￿￿￿m^ֳ￿kU￿t￿6)￿Zjqz"0dҳ￿yd#￿3֘R￿￿k￿MY￿2'￿￿ɽd￿O￿"BX￿￿￿,￿ ￿￿￿￿￿￿￿A￿VG ]3
It seems that the files were encoded differently. What do you guys think?