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
[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.
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.
$.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:
PK ú‚ÐJmÇ´¸g € BOM.csvu'ËNÃ0?E÷HüÃÈ+ÆÑØy/›”WÔðH[Ä64IÕ¦|?>‰_ÀN(-¢l®,Ýã;wìÏ÷‡m^Ö³ú 35VkUŽtÕf6)óºZcZjqz"0?dÒ³ü9TÓ%yd#ˆ3Ö˜R›¡kÙMYæt?2'Òâ¦É½dÈhO¶"BXÁ?ùÚ”Ç<‰,ÖÍ '?ååÎé ÁÝ!Ò ²AˆVG ]3?
PK ￿￿￿g ￿ BOM.csvu￿￿￿?E￿￿+￿￿/￿￿W￿H[￿4Iզ|?>￿_￿(-￿l￿,￿;w￿￿￿m^ֳ￿kU￿t￿6)￿Zjqz"0?dҳ￿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?
Thank you Musa for giving me that clue.
Now here is the Service Call I am using to download my Zip File:
var xhrq = new XMLHttpRequest();
xhrq.onreadystatechange = function () {
if (this.readyState == 4 ) {
if (this.status == 200) {
var xhrp = this;
var response = this.response;
// check for a filename
var filename = "";
var disposition = xhrp.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 = xhrp.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type, encoding: "UTF-8" });
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;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
} else {
// Call Back for Error
}
}
}
// Open HTTP Request and Call API Function
xhrq.open("POST", appPath + "DownloadZipFile");
xhrq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhrq.responseType = 'blob';
xhrq.send('designData=' + escape(JSON.stringify(zipData)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.