MVC Asp.net zip file download - javascript

I have some code in an MVC project that creates a zip file and sends it to the browser. Everything works when I manually enter the URL in the browser, but if I click on the link in the page to get the download, I get a file of a different size and Windows cannot open it.
So, if I manually enter something like this:
http://localhost/fms-ui/File/DownloadZipFile/?id=10&filename=DST-2015-11-14_04_04_04
I get a zip file of 167 bytes and it open fine.
If I click on the link in the page, I get a file of 180 bytes and Windows says the file is corrupted. Hun?
My one stipulation is that I cannot use an external library. Due to politics I must use the library provided with .Net Framework 4.5 (static ZipFile class).
Code:
public FileContentResult DownloadZipFile(int id, string filename)
{
/*
* 1 - get fileset info
* 2 - get temp file name
* 3 - create zip file under temp name
* 4- return file
*/
QuesterTangent.Wayside.FileServices.FileSet sInfo = new QuesterTangent.Wayside.FileServices.FileSet(id);
string path = Path.Combine(sInfo.BasePath);
string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".zip");
ZipFile.CreateFromDirectory(path, tempPath);
byte[] fileBytes = System.IO.File.ReadAllBytes(tempPath);
//System.IO.File.Delete(tempPath); Commented so I can compare the files
filename = filename + ".zip";
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileBytes, "application/zip");
}
I've tried this with and without AppendHeader and with various contentTypes, but it doesn't seem to effect the outcome.
Here is the JavaScript that calls the controller (I inherited this code but it works for other things).
function GetFile(url) {
//spin a wheel for friendly buffering time
var buffer = $('.MiddleRightDiv').spinBuffer();
$.ajax({
url: url,
type: "POST",
cache: false,
async: true,
data: {},
success: function (response, status, xhr) {
// check for a filename
var filename = "";
var disposition = xhr.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 = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
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
}
},
complete: function (result) {
if (typeof $('.MiddleRightDiv').spinBuffer !== 'undefined' && $.isFunction($('.MiddleRightDiv').spinBuffer)) {
$('.MiddleRightDiv').spinBuffer("destroy");
}
}
});
Any input would be a great help. I have gone over other similar postings but non of them seems to address the core problem I am having.
Thanks,
dinsdale

jQuery.ajax cannot read bytestreams correctly (check SO for many topics about this), so we have to use old and good XMLHttpRequest. Here is your function refactored to work with blobs. Extened it with fallbacks for other browsers while saveAs(blob,filename) is the draft.
function GetFile(url) {
if (window.navigator.msSaveBlob) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
req.onload = function (e) {
if (req.response) {
var filename = 'archive.zip';
var disposition = req.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 = req.getResponseHeader('Content-Type');
var blob = new Blob([req.response], { type: type ? type : 'application/octet' });
window.navigator.msSaveBlob(blob, filename);
} else {
throw 'Empty or invalid response';
}
}
req.send();
} else {
//fallback for browsers without blob saver
throw 'Not implemented';
}
}

Related

File uploaded does not upload if the file name has parenthesis ()

I have a FileUpload control where I upload PDF files and they get saved to a folder, the file path gets saved to the database.
The problem is when I upload a file which contains parenthesis () as part of the file name, it returns undefined. This only happens if the file name has parenthesis () , if it does not have parenthesis () it uploads fine.
This is my code
var filePaths;
function UploadFile() {
var fileUpload = document.getElementById("fuPDFupload");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.pdf)$");
if (regex.test(fileUpload.value.toLowerCase())) {
//Check whether HTML5 is supported.
if (typeof (fileUpload.files) != "undefined") {
//Initiate the FileReader object.
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
var fileUpload = $("#fuPDFupload").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
url: "FileUploadHandler.ashx",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (result) {
filePaths = result;
//Save to DB
UpdateSchedule();
},
error: function (err) {
}
});
return true;
};
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
return false;
}
}
FileUploadHandler Code:
public class FileUploadHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
string filePaths = Guid.NewGuid().ToString() + ".pdf";
HttpPostedFile file = context.Request.Files[0];
string path = context.Server.MapPath("~/QfrencyInvoices/" + filePaths);
file.SaveAs(path);
context.Response.ContentType = "text/plain";
context.Response.Write(filePaths);
}
}
public bool IsReusable {
get {
return false;
}
}
}
I believe that the problem might be happening because the Regex expression is incorrect but I have not been able to fix it.
Please assist me how I can upload files that have parenthesis () as part of the file name. Thank you.
Just leave next regex new RegExp("(\.(jpg|png|pdf)$", "i");. It checks that filename has extension jpg, png or pdf. Text case does not matter so "i" was added as the second parameter.
You can learn regular expressions on https://regexone.com/

Download a file on Autodesk Forge using .NET

I am unsure how to download objects inside a bucket. The file I am currently able to download has a significantly smaller size compared to the file uploaded in the bucket. In addition, I am unable to open the file after it is downloaded. Is there something missing in my code? The following code is what I used to download files.
var element = document.createElement('a');
element.setAttribute('href', '#');
element.setAttribute('download', node.text);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
You refer my answer here (Download BIM360 Docs file using Javascript) to download files from Forge OSS bucket.
In this suggestion, I extended the jQuery function to creates new XMLHttpRequest and passes all the received data back to the jQuery.
/**
*
* jquery.binarytransport.js
*
* #description. jQuery ajax transport for making binary data type requests.
* #version 1.0
* #author Henry Algus <henryalgus#gmail.com>
*
*/
// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR) {
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
return {
// create new XMLHttpRequest
send: function(headers, callback) {
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
async = options.async || true,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null,
username = options.username || null,
password = options.password || null;
xhr.addEventListener('load', function() {
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});
xhr.open(type, url, async, username, password);
// setup custom headers
for (var i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
xhr.responseType = dataType;
xhr.send(data);
},
abort: function() {
jqXHR.abort();
}
};
}
});
Afterward, you can simply replace values of filename, bucketKey and YOUR_ACCESS_TOKEN to yours to download files on the website directly. However, it could be very unsafe, please see the comment here
$(function() {
$('a#download').click(function(event) {
event.preventDefault();
const filename = 'hose.rvt';
const bucketKey = 'adn-test';
const settings = {
crossDomain: true,
url: 'https://developer.api.autodesk.com/oss/v2/buckets/' + bucketKey + ' /objects/' + filename,
method: 'GET',
dataType: 'binary',
processData: false,
headers: {
Authorization: 'Bearer YOUR_ACCESS_TOKEN',
Content-Type: 'application/octet-stream'
}
};
$.ajax(settings).done(function (blob, textStatus, jqXHR) {
console.log(blob );
console.log(textStatus);
if( navigator.msSaveBlob )
return navigator.msSaveBlob(blob, filename);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style = 'display: none';
document.body.appendChild(a);
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
});
});
})

Reading Blob of a file in javascript and inserting in database

I want to read any kind of file from my js code and insert its blob to database in long blob type column. Variable in js is reading blob as string but not as blob.
So I am facing issue if there are special characters like single/double quote etc.
reading code is
function onChooseFile(event, onLoadFileHandler) {
if (typeof window.FileReader !== 'function')
throw ("The file API isn't supported on this browser.");
let input = event.target;
if (!input)
throw ("The browser does not properly implement the event object");
if (!input.files)
throw ("This browser does not support the `files` property of the file input.");
if (!input.files[0])
return undefined;
let file = input.files[0];
let fr = new FileReader();
fr.onload = onLoadFileHandler;
fr.onloadend = function(event) {
if (event.target.readyState == FileReader.DONE) { // DONE == 2
//blobData = event.target.result;
blobData = new Blob([event.target.result], { type: fileType });
console.log(blobData);
console.log(typeof(blobData));
console.log(blobData instanceof Blob)
console.log("-------------------------------------------------");
blobString = ab2str(event.target.result);
console.log(blobData);
alert("file read complete "+blobData.length);
}
};
document.getElementById('inputHeader').value = file.name;
fileName = file.name;
fileType = file.type;
fileExtension = fileName.split(".").pop();
fr.readAsBinaryString(file);
}
Writing Code is
dataservice.openDocument(document_version_id)
.done(function (reply) {
fileExtension = fileName.split(".").pop();
switch(fileExtension.toLowerCase()){
case "doc":
case "docx":
fileType = "application/msword";
break;
case "pdf":
fileType = "application/pdf";
break;
case "xls":
case "xlsx" :
fileType = "application/vnd.ms-excel";
break;
}
var blob = new Blob([reply.RECORD_DATA.LONG_BLOB], { type: fileType });
saveAs(blob, 'C:/OutputFile/hello.'+fileExtension);
deferred.resolve();
}).fail(function (error) {
alert("failure in getting document");
deferred.reject();
});
});
Please help, how to achieve this.
Thanks

octet stream download as csv doesn't work in IE [duplicate]

I have this in my Angular.js controller that downloads a CSV file:
var blob = new Blob([csvContent.join('')], { type: 'text/csv;charset=utf-8'});
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
This works perfectly in Chrome but not in IE. A browser console log says:
HTML7007: One or more blob URLs were revoked by closing the blob for
which they were created. These URLs will no longer resolve as the data
backing the URL has been freed.
What does it mean and how can I fix it?
Try this using, this or useragent
if (navigator.appVersion.toString().indexOf('.NET') > 0)
window.navigator.msSaveBlob(blob, filename);
else
{
var blob = new Blob(['stringhere'], { type: 'text/csv;charset=utf-8' });
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
}
IE won't allow you to open blobs directly. You have to use msSaveOrOpenBlob. There's also msSaveBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
I needed to use a Blob to download a converted a base64 PNG image. I was able to successfully download the blob on IE11 with window.navigator.msSaveBlob
See the following msdn link:
http://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx
Specifically, you should call:
window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt');
where blobObject is a Blob created in the usual fashion.
Complete Solution for Chrome, Internet Explorer Firefox and Opera
There are lots of nice bits on this page, but I had to use a combination of a few things to get it all to work. Hopefully this helps you.
Use a button or link to trigger a function called download():
<button class="button-no save-btn" ng-click="download()">DOWNLOAD</button>
Put this in your controller:
$scope.download = function () {
// example shows a JSON file
var content = JSON.stringify($scope.stuffToPutInFile, null, " ");
var blob = new Blob([content], {type: 'application/json;charset=utf-8'});
if (window.navigator && window.navigator.msSaveBlob) {
// Internet Explorer workaround
$log.warn("Triggering download using msSaveBlob");
window.navigator.msSaveBlob(blob, "export.json");
} else {
// other browsers
$log.warn("Triggering download using webkit");
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create invisible element
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href', url);
downloadLink.attr('download', 'export.json');
// make link invisible and add to the DOM (Firefox)
downloadLink.attr('style','display:none');
angular.element(document.body).append(downloadLink);
// trigger click
downloadLink[0].click();
}
};
What's your IE browser version? You need a modern browser or IE10+
http://caniuse.com/bloburls
Maybe you need some delay. What about with:
link.click();
setTimeout(function(){
document.body.createElementNS('http://www.w3.org/1999/xhtml', 'a');
URL.revokeObjectURL(link.href);
}, 100);
I needed to get the download feature to work in Chrome and IE11. I had good success with this code.
HTML
<div ng-repeat="attachment in attachments">
<a ng-click="openAttachment(attachment)" ng-href="{{attachment.fileRef}}">{{attachment.filename}}</a>
</div>
JS
$scope.openAttachment = function (attachment) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(
b64toBlob(attachment.attachment, attachment.mimeType),
attachment.filename
);
}
};
Done it this way, working fine for me.
downloadFile(data) {
if (navigator.msSaveBlob) {
let blob = new Blob([data], {
"type": "text/csv;charset=utf8;"
});
navigator.msSaveBlob(blob, this.fileName);
}
else {
let blob = new Blob(['\ufeff' + data], { type: 'text/csv;charset=utf-8;' });
let $link = document.createElement("a");
let url = URL.createObjectURL(blob);
$link.setAttribute("target", "_blank");
$link.setAttribute("href", url);
$link.setAttribute("download", this.fileName);
$link.style.visibility = "hidden";
document.body.appendChild($link);
$link.click();
document.body.removeChild($link);
}
}
Try to use this instead :
var blob = file.slice(0, file.size);
Create polyfill method as below,had a variable filename since in my case download filename was static.This method will be called while blob function is not supported as in case of Internet explorer
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype,
'toBlob', {
value: function (callback, type, quality) {
var canvas = this;
setTimeout(function () {
var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
var blob = new Blob([arr], {
type: 'image/png'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
});
}
});
}
try {
const blob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
const file = new File([blob], this.getFileName(res), {
type: res.headers.get('Content-Type'),
});
saveAs(file);
} catch (err) {
var textFileAsBlob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
window.navigator.msSaveBlob(textFileAsBlob, this.getFileName(res));
}
To get the file name. Use the below function.
getFileName(response: any) {
let name: string;
try {
const contentDisposition: string = response.headers.get(
'content-disposition'
);
const [, filename] = contentDisposition.split('filename=');
name = filename;
} catch (e) {
name = 'File_Name_Not_Specified_' + new Date();
}
return name;
}
This worked for me.

Blob download is not working in IE

I have this in my Angular.js controller that downloads a CSV file:
var blob = new Blob([csvContent.join('')], { type: 'text/csv;charset=utf-8'});
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
This works perfectly in Chrome but not in IE. A browser console log says:
HTML7007: One or more blob URLs were revoked by closing the blob for
which they were created. These URLs will no longer resolve as the data
backing the URL has been freed.
What does it mean and how can I fix it?
Try this using, this or useragent
if (navigator.appVersion.toString().indexOf('.NET') > 0)
window.navigator.msSaveBlob(blob, filename);
else
{
var blob = new Blob(['stringhere'], { type: 'text/csv;charset=utf-8' });
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
}
IE won't allow you to open blobs directly. You have to use msSaveOrOpenBlob. There's also msSaveBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
I needed to use a Blob to download a converted a base64 PNG image. I was able to successfully download the blob on IE11 with window.navigator.msSaveBlob
See the following msdn link:
http://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx
Specifically, you should call:
window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt');
where blobObject is a Blob created in the usual fashion.
Complete Solution for Chrome, Internet Explorer Firefox and Opera
There are lots of nice bits on this page, but I had to use a combination of a few things to get it all to work. Hopefully this helps you.
Use a button or link to trigger a function called download():
<button class="button-no save-btn" ng-click="download()">DOWNLOAD</button>
Put this in your controller:
$scope.download = function () {
// example shows a JSON file
var content = JSON.stringify($scope.stuffToPutInFile, null, " ");
var blob = new Blob([content], {type: 'application/json;charset=utf-8'});
if (window.navigator && window.navigator.msSaveBlob) {
// Internet Explorer workaround
$log.warn("Triggering download using msSaveBlob");
window.navigator.msSaveBlob(blob, "export.json");
} else {
// other browsers
$log.warn("Triggering download using webkit");
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create invisible element
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href', url);
downloadLink.attr('download', 'export.json');
// make link invisible and add to the DOM (Firefox)
downloadLink.attr('style','display:none');
angular.element(document.body).append(downloadLink);
// trigger click
downloadLink[0].click();
}
};
What's your IE browser version? You need a modern browser or IE10+
http://caniuse.com/bloburls
Maybe you need some delay. What about with:
link.click();
setTimeout(function(){
document.body.createElementNS('http://www.w3.org/1999/xhtml', 'a');
URL.revokeObjectURL(link.href);
}, 100);
I needed to get the download feature to work in Chrome and IE11. I had good success with this code.
HTML
<div ng-repeat="attachment in attachments">
<a ng-click="openAttachment(attachment)" ng-href="{{attachment.fileRef}}">{{attachment.filename}}</a>
</div>
JS
$scope.openAttachment = function (attachment) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(
b64toBlob(attachment.attachment, attachment.mimeType),
attachment.filename
);
}
};
Done it this way, working fine for me.
downloadFile(data) {
if (navigator.msSaveBlob) {
let blob = new Blob([data], {
"type": "text/csv;charset=utf8;"
});
navigator.msSaveBlob(blob, this.fileName);
}
else {
let blob = new Blob(['\ufeff' + data], { type: 'text/csv;charset=utf-8;' });
let $link = document.createElement("a");
let url = URL.createObjectURL(blob);
$link.setAttribute("target", "_blank");
$link.setAttribute("href", url);
$link.setAttribute("download", this.fileName);
$link.style.visibility = "hidden";
document.body.appendChild($link);
$link.click();
document.body.removeChild($link);
}
}
Try to use this instead :
var blob = file.slice(0, file.size);
Create polyfill method as below,had a variable filename since in my case download filename was static.This method will be called while blob function is not supported as in case of Internet explorer
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype,
'toBlob', {
value: function (callback, type, quality) {
var canvas = this;
setTimeout(function () {
var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
var blob = new Blob([arr], {
type: 'image/png'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
});
}
});
}
try {
const blob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
const file = new File([blob], this.getFileName(res), {
type: res.headers.get('Content-Type'),
});
saveAs(file);
} catch (err) {
var textFileAsBlob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
window.navigator.msSaveBlob(textFileAsBlob, this.getFileName(res));
}
To get the file name. Use the below function.
getFileName(response: any) {
let name: string;
try {
const contentDisposition: string = response.headers.get(
'content-disposition'
);
const [, filename] = contentDisposition.split('filename=');
name = filename;
} catch (e) {
name = 'File_Name_Not_Specified_' + new Date();
}
return name;
}
This worked for me.

Categories