Angular 1 download file from ajax response - javascript

I'm generating an excel file in my MVC controller using EPPLUS.
And I'm invoking the controller method from angular js controller using a ajax request
$scope.agreedFlow = function () {
var ajaxexcelDownload = AgreedFlowService.GenerateAgreedFlow({
});
$q.all([ajaxexcelDownload]).then(function (responses) {
});
};
And my angular service
self.GenerateAgreedFlow = function (data, callback) {
ajaxService.post({
url: '/Plan/GenerateAgreedFlow'
, data: data
, dataType: 'json'
, responseType: 'arraybuffer'
, cache: false
}).done(function (result) {
if (typeof callback === "function")
callback(result);
}).fail(function () {
});
};
And my MVC Controller method
public void GenerateAgreedFlow()
{
var planService = ServiceFactory.PlanService;
var fileName = "ExcellData.xlsx";
var file = new FileInfo( fileName);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("AgreedPlan " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
DataTable dt =planService.GetAgreedYarnFlow();
int iCol = 1;
// Add column headings...
foreach (DataColumn c in dt.Columns)
{
worksheet.Cells[1, iCol].Value = c.ColumnName;
worksheet.Cells[1, iCol].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, iCol].Style.Fill.BackgroundColor.SetColor(Color.LightGray);
iCol++;
}
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
worksheet.Cells[j + 2, k + 1].Value = dt.Rows[j].ItemArray[k].ToString();
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 1)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
}
}
var colCount = dt.Columns.Count;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.Column(1).Hidden = true;
worksheet.Column(2).Hidden = true;
worksheet.Column(3).Hidden = true;
worksheet.Column(4).Hidden = true;
worksheet.Column(5).Hidden = true;
worksheet.Column(8).Hidden = true;
worksheet.Protection.IsProtected = true;
// save our new workbook and we are done!
package.Workbook.Properties.Title = "Attempts";
this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
this.Response.AddHeader(
"content-disposition",
string.Format("attachment; filename={0}", "ExcellData.xlsx"));
this.Response.BinaryWrite(package.GetAsByteArray());
}
Is there any way to download file from the ajax response ??

Related

Uploading files via axios to WebApi

I'm getting this error when trying to upload a file to webapi
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'
javascript:
UploadReceivingIssueImages(e) {
if (!e.target.files || e.target.files.length === 0)
return;
let formData = new FormData();
for (var i = 0; i < e.target.files.length; i++) {
formData.append('file', e.target.files[i]);
}
var vm = this;
axios.post('../api/receiving/UploadDocReceivingIssueImages?headerId=' + this.SelectedSubIdIdObj.HeaderId,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
vm.getDocReceivingIssueImages();
console.log('SUCCESS!!');
}, function (er) {
alert("Couldn't upload images")
});
}
WebApi Code
[HttpPost]
public bool UploadDocReceivingIssueImages([FromUri] int headerId)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count < 1)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("No File Uploaded"),
ReasonPhrase = "No File Uploaded"
};
throw new HttpResponseException(resp);
}
var dirPath = #"\\dirPath";
foreach (var f in httpRequest.Files)
{
var pf = (System.Web.HttpPostedFile)f;
pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
}
return true;
}
the error happens at
var pf = (System.Web.HttpPostedFile)f;
the f object is a string with value 'file'... WHY?!?!
any help would be appreciated.
Because when you enumerate over HttpRequest.PostedFiles you're enumerating over its keys (the names, which are all 'file' based on your JS), not the files:
foreach (var key in httpRequest.Files)
{
var pf = httpRequest.Files[key]; // implicit cast to HttpPostedFile
pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
}
EDIT TO ADD:
With that said, you'll need to update your JS to use unique names in FormData or else you'll only be able to read one file out of your HttpContext's HttpFileCollection:
for (var i = 0; i < e.target.files.length; i++) {
formData.append('file' + i, e.target.files[i]);
}
See HttpFileCollection on MSDN

JS one of my functions does not seem to exist

I have a function :
var postBet = function(enemyID, ip_1, ip_2, playerID) {
$.post("save.php", {
enemyID: enemyID,
ip_1: ip_1,
ip_2: ip_2,
playerID: playerID
},
function(data, status) {
document.getElementById("saveWarningText").innerHTML = data;
$("#saveWarningText").fadeIn(100);
setTimeout(function() {
$("#saveWarningText").fadeOut(100);
}, 3000);
}
);
};
Unlike all of my other functions when I attempt to call it I get: Uncaught ReferenceError: postBet is not defined
Update
Full code:
var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
var doCORSRequest = function(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = x.onerror = function() {
printResult(
(x.responseText || '')
);
};
if (/^POST/i.test(options.method)) {
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
x.send(options.data);
};
var playerIDs = [""];
var playerNames = [""];
var playerScores = [""];
var enemyIDs = [""];
var enemyNames = [""];
var enemyScores = [""];
var parser2 = new DOMParser();
var xmlDoc2;
var done1 = false;
var done2 = false;
var step1 = function() {
for (var i = 0; i < playerIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=playerScores&L=" + document.getElementById('code').value + "&RULES&PLAYERS=";
url2 = url2 + playerIDs[i] + ",";
var out2 = "";
callback1(i, url2);
if (i >= playerIDs.length - 1) {
done1 = true;
}
}
for (var i = 0; i < enemyIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=playerScores&L=" + document.getElementById('code').value + "&RULES&PLAYERS=";
url2 = url2 + enemyIDs[i] + ",";
var out2 = "";
callback2(i, url2);
if (i >= playerIDs.length - 1) {
done2 = true;
}
}
if (done1 && done2) {
step2();
}
};
var callback1 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2,
}, function printResult(result) {
out2 = result;
xmlDoc2 = parser2.parseFromString(out2, "text/xml");
var temp = 0;
for (var j = 0; j < parseInt(xmlDoc2.getElementsByTagName('playerScore').length) - 1; j++) {
if (xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score') !== "") {
temp = temp + parseInt(xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score'));
}
playerScores[i] = temp;
}
});
};
var callback2 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2,
}, function printResult(result) {
out2 = result;
xmlDoc2 = parser2.parseFromString(out2, "text/xml");
var temp = 0;
for (var j = 0; j < parseInt(xmlDoc2.getElementsByTagName('playerScore').length) - 1; j++) {
if (xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score') !== "") {
temp = temp + parseInt(xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score'));
}
enemyScores[i] = temp;
}
});
};
var step2 = function() {
for (var i = 0; i < playerIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=players&PLAYERS=";
url2 = url2 + playerIDs[i];
callback3(i, url2);
}
for (var i = 0; i < enemyIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=players&PLAYERS=";
url2 = url2 + enemyIDs[i];
callback4(i, url2);
}
};
var callback3 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2
}, function printResult(result) {
xmlDoc2 = parser2.parseFromString(result, "text/xml");
playerNames[i] = xmlDoc2.getElementsByTagName('player')[0].getAttribute('name');
var option = document.createElement("option");
var node = document.createTextNode(playerNames[i] + " : " + playerScores[i]);
option.appendChild(node);
var element = document.getElementById("you");
element.appendChild(option);
});
};
var callback4 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2
}, function printResult(result) {
xmlDoc2 = parser2.parseFromString(result, "text/xml");
enemyNames[i] = xmlDoc2.getElementsByTagName('player')[0].getAttribute('name');
var option = document.createElement("option");
var node = document.createTextNode(enemyNames[i] + " : " + enemyScores[i]);
option.appendChild(node);
var element = document.getElementById("enemy");
element.appendChild(option);
});
};
var postBet = function(enemyID, ip_1, ip_2, playerID) {
$.post("save.php", {
enemyID: enemyID,
ip_1: ip_1,
ip_2: ip_2,
playerID: playerID
},
function(data, status) {
document.getElementById("saveWarningText").innerHTML = data;
$("#saveWarningText").fadeIn(100);
setTimeout(function() {
$("#saveWarningText").fadeOut(100);
}, 3000);
}
);
};
(function() {
postBet('1', '1', '1', '1');
document.getElementById('start').onclick = function(e) {
var url = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=rosters&L=" + document.getElementById('code').value;
var data = "";
var output = "";
var parser = new DOMParser();
var xmlDoc;
var n1 = document.getElementById("you");
while (n1.firstChild) {
n1.removeChild(n1.firstChild);
}
var n2 = document.getElementById("enemy");
while (n2.firstChild) {
n2.removeChild(n2.firstChild);
}
e.preventDefault();
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url,
data: data
}, function printResult(result) {
output = result;
xmlDoc = parser.parseFromString(output, "text/xml");
for (var i = 1; i < xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length; i += 2) {
playerIDs.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length / 2) - 1);
playerScores.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length / 2) - 1);
playerIDs[Math.round(i / 2) - 1] = xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes[i].getAttribute('id');
}
for (var i = 1; i < xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes.length; i += 2) {
enemyIDs.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes.length / 2) - 1);
enemyIDs[Math.round(i / 2) - 1] = xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes[i].getAttribute('id');
}
step1();
});
};
})();
Turns out 000webhost was using a cached version of the website. It was using an older version of my code without that function. Fixed the problem by deleting and re-uploading my code to 000webhost.

Javascript - FileReader how can I read and process each file at a time among multiple files

I am trying let the user drop multiple excel file and extract desired values from each one of the files and upload it to website ONE FILE AT A TIME.
My code is not working, and I am assuming this is because of the callback problem..
Could anybody help?
Edit: I also added my uploadFile function. I very much appreciate your help.
for(var i = 0; i < fileList.length; i++) {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if(!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try{
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if(ein == undefined || engCode == undefined || goLocator == undefined){
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if(hasValues && isValid){
uploadFile(fileList[i], userInfo);
} else {
noValueErrorHandler(errMsg);
}
} catch(err){
hasValues = false;
}
};
if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
function uploadFile(f, userInfo) {
// Define the folder path for this example.
var serverRelativeUrlToFolder = listName;
// Get info of the file to be uploaded
var file = f;
var fileInput = file["file"];
var newName = file["fileName"];
var ein = file["EIN"];
var engCode = file["EngagementCode"];
var email = userInfo;
var goLocator = file["GoSystem"];
console.log("file: " + file);
// Get the server URL.
var serverUrl = _spPageContextInfo.siteAbsoluteUrl + "/StatusTracker";
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileInput);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer, newName);
addFile.done(function (file, status, xhr) {
// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {
// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
processedCount += 1;
if (processedCount < fileCount) {
uploadFile(fileList[processedCount], email);
} else if (processedCount == fileCount){
$("#dropbox").text("Done, drop your next file");
$("#ADMNGrid").data("kendoGrid").dataSource.read();
fileList = [];
alert("Total of " + processedCount + " items are processed!");
}
// Refresh kendo grid and change back the message and empty fileList
//$("#dropbox").text("Drag your Fund/Lower Tier workpaper here ...");
//location.reload(true);
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
You might put the whole thing into an async function and await a Promise for each iteration, forcing the files to be processed in serial. You didn't post your uploadFile, but if you have it return a Promise that resolves once it's done, you could do the following:
async fn() {
for (var i = 0; i < fileList.length; i++) {
await new Promise((resolve, reject) => {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if (!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {
type: rABS ? 'binary' : 'array'
});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try {
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if (ein == undefined || engCode == undefined || goLocator == undefined) {
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if (hasValues && isValid) {
uploadFile(fileList[i], userInfo)
.then(resolve);
} else {
noValueErrorHandler(errMsg);
reject();
}
} catch (err) {
hasValues = false;
reject();
}
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
});
}
}

How to parse a csv file using sapui5 FileUploader controller

I want to get a file from client side to parse it into json object and send it to the backend, i am able to parse the file thanks to Sheet-js.
My problem is i can not get files from client side
I am using js, SAPUI5
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
if (!oFileUploader.getValue().toString()) {
MessageToast.show("Choose a xlsx file first");
return;
}
var url = "/resources/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = [];
for (var i = 0; i !== data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {
type: "binary"
});
var firstSheetName = workbook.SheetNames[0];
var worksheet = workbook.Sheets[firstSheetName];
var json = XLSX.utils.sheet_to_json(worksheet, {
raw: true
});
var jsonStr = JSON.stringify(json);
MessageBox.show("JSON String: " + jsonStr);
};
oReq.send();
},
The answer is:
UploadFile.view.xml
<VBox>
<u:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}

How do I delete multiple files at once in Drive API for Javascript?

function deleteFiles(fileId,supportsTeamDrives) {
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0] ;
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = "+test+" and viewedByMeTime < '"+n+"'",
orderBy: 'quotaBytesUsed desc',
fields: "nextPageToken, files(id, name, viewedByMeTime, mimeType, quotaBytesUsed)",
}
)
.then(function(response) {
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var file_id = file.id,
)');
}}
var request = gapi.client.drive.files.delete({
supportsTeamDrives: 'false',
fileId: file_id ,
}); }
request.execute(function(resp) { });
}
I want this function to list out the fileIDs, as as each fileID is put out, they get deleted. How do I combine list file and delete file functions together for this to work?
Currently I separated them into two functions, but the variable fileID only saves the last fileID outputted, thus, the delete function would only delete one file, the last file listed. I want it to list and output every file to a varable and as its listed it gets deleted. What can I change or add in my goal to accomplish this?
You can alter your code to delete the file in your loop:
function deleteFiles(fileId, supportsTeamDrives) {
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0];
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = " + test + " and viewedByMeTime < '" + n + "'",
orderBy: 'quotaBytesUsed desc',
fields: "nextPageToken, files(id, name, viewedByMeTime, mimeType, quotaBytesUsed)",
}
)
.then(function(response) {
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var file_id = file.id;
deleteFile(file_id);
}
}
});
}
// method used to delete the files
function deleteFile(file_id) {
var request = gapi.client.drive.files.delete({
supportsTeamDrives: 'false',
fileId: file_id,
});
request.execute(function(resp) {});
}

Categories