Pass Javascript data from one function to another - javascript

I need to get an image file and post it using http in angular. Angular does not model files so I need a separate function to grab the data.
How can I pass data from this function to my http request?
var f = document.getElementById('imageFile').files[0],
r = new FileReader();
r.onloadend = function(e){
var data = e.target.result;
//***********************************************
// This is where my data is
//***********************************************
}
r.readAsArrayBuffer(f);
var request = $http({
method: "post",
url: "/data/addToStore.php",
data: {
product_code: $scope.product_code,
product_name: $scope.product_name,
autoship_price: $scope.autoship_price,
regular_price: $scope.regular_price,
product_category_main: $scope.product_category_main,
product_desc: $scope.product_desc,
cat: $scope.cat,
/* ********************************************
This is where I need to get my data to
imageFile: $SOMETHING
******************************************** */
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

As per my comment above:
var fileData = null;
var f = document.getElementById('imageFile').files[0],
r = new FileReader();
r.onloadend = function(e){
fileData = e.target.result;
//***********************************************
// This is where my data is
//***********************************************
}
r.readAsArrayBuffer(f);
var request = $http({
method: "post",
url: "/data/addToStore.php",
data: {
product_code: $scope.product_code,
product_name: $scope.product_name,
autoship_price: $scope.autoship_price,
regular_price: $scope.regular_price,
product_category_main: $scope.product_category_main,
product_desc: $scope.product_desc,
cat: $scope.cat,
imageFile: fileData
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

You could refactor that into a method callback on the scope object:
$scope.getFile = function (){
var f = document.getElementById('imageFile').files[0];
var r = new FileReader();
r.onloadend = function(e){
var data = e.target.result;
}
return r.readAsArrayBuffer(f);
}
var request = $http({
method: "post",
url: "/data/addToStore.php",
data: {
product_code: $scope.product_code,
product_name: $scope.product_name,
autoship_price: $scope.autoship_price,
regular_price: $scope.regular_price,
product_category_main: $scope.product_category_main,
product_desc: $scope.product_desc,
cat: $scope.cat,
fileData: $scope.getFile()
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

Related

Convert Excel file to json with XLSX javascript library

I want to get an excel file and parse it into a json so I can send it to the backend as a string object.
I import the library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.7/xlsx.js"></script>
I get the file with an html input control:
var project;
$(':file').on('change', function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
var filename = this.files[0].name.toLowerCase();
var exceljson;
if (regex.test(filename)) {
if (filename.indexOf(".xlsx") > 0) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
}
reader.readAsArrayBuffer(this.files[0]);
}
}
}
project = {
id: dt.rows('.selected').data()[0].id,
projectname: dt.rows('.selected').data()[0].projectname,
file: exceljson
}
$.ajax({
url: urlBack + '/******/importData',
type: 'POST',
headers: { "userId": ******, "token": ****** },
contentType: 'application/json',
data: JSON.stringify(project),
success: function (result) {
$('#table').DataTable().ajax.reload(null, false);
$('.modal').modal('hide');
swal(swalProjectAdded, "", "success");
},
error: function (result) {
$('#table').DataTable().ajax.reload(null, false);
$('.modal').modal('hide');
swal(swalError, "", "error");
}
});
});
$(':file').trigger("click");
but when I run it I get this error:
Uncaught Error: Cannot find file [Content_Types].xml in zip
at getzipfile (xlsx.js:2928)
at getzipstr (xlsx.js:2939)
at parse_zip (xlsx.js:20612)
at read_zip (xlsx.js:20946)
at Object.readSync [as read] (xlsx.js:21012)
at FileReader.reader.onload (projects:189)
I have followed the instructions to run the library so I don't understand what's happening.

$http.post() freezing chrome browser after file upload the file for import

I am stuck, where is the memory leakages?
What I am trying?
After import the .xlsx (store) I am fetching them again in the response (I also try to fetch them independently on other ele click event ).
Problem:
After uploading 2 -3 files chrome browser freeze on $http.post(...) ( Working fine in FF), I have added code sample.
Thanks!
/***** HTML *****
<input type="file" onchange="angular.element(this).scope().storeBulkUpdate(this)">
*****/
/*** Controller */
var paginationCriteria = {
pageNo: 1,
size: 10
};
$scope.getAllStoreStores = function (_data, qParam) {
storeSevice.getStore(_data, $httpParamSerializer(qParam)).success(function (data) {
console.log(data)
});
}
$scope.storeBulkUpdate = function (element) {
var fileData = element.files[0];
var formData = new FormData();
formData.append('file', fileData);
storeSevice.bulkUpdateStore(formData).success(function (data, status, headers, config) {
$scope.getAllStore({}, paginationCriteria);
});
};
/**Factory 'storeSevice' */
return {
bulkUpdateStore: function (_postData) {
url = '/upload'
//Set Headers
var header = {};
var extendedHeader = AuthenticationService.createAuthorizationHeader(
header,
url,
'POST',
_postData
);
extendedHeader['ServiceName'] = 'uploadMTTForStore';
extendedHeader['Content-Type'] = undefined;
//Headers End
return $http.post(url, _postData, {
withCredentials: false,
headers: extendedHeader,
transformRequest: angular.identity
});
},
getStore: function (_postData, $parameters) {
url = '/getStore?' + $parameters;
var header = {};
var extendedHeader = AuthenticationService.createAuthorizationHeader(
header,
url,
'POST'
);
extendedHeader['ServiceName'] = 'storeFetch';
//browser feerze
return $http.post(url, $postData, {
headers: extendedHeader
});
},
otherMethods: "etc......."
}

Get weather data from openweathermap

How to get the temperature of the JSON data, rain, clouds, etc?
The name normal returns, but other parameters are undefended or error.
http://jsbin.com/qayobod/edit?html,js,console,output
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function($http) {
var vm = this;
var temp1 = [];
var URL = 'http://api.openweathermap.org/data/2.5/forecast/daily';
var request = {
method: 'GET',
url: URL,
params: {
q: 'KansasCity',
mode: 'json',
units: 'imperial',
cnt: '7',
appid: '3ac1f68b653ffbf72a5f782420062771'
}
};
$http(request).then(function(response) {
vm.data = response.data;
temp1[0] = angular.fromJson(response.data);
console.log(temp1[0]);
console.log(temp1[0].city.name);
console.log(temp1[0].city.country);
console.log(temp1[1].temp.day);
}).catch(function(response) {
vm.data = response.data;
});
console.log(temp);
});

sending FormData with angular $http

I'm writing an angular-1.5.0-rc0 application
In this application I create FormData, fill it with values and I need to send it with $http request. for now I use jquery ajax with the following code:
this.addDrink = function () {
var data = new FormData();
var drinkBrand = caller.drink.drinkBrand;
var drinkType = caller.drink.drinkType;
var drinkFlavor = caller.drink.drinkFlavor;
var liquidColor = caller.drink.liquidColor;
var drinkCompany = caller.drink.drinkCompany;
var liquidIsTransparent = caller.drink.liquidIsTransparent;
var drinkImage = caller.drink.drinkImage;
var caloriesFor100g = caller.drink.caloriesFor100g;
var alcoholSum = caller.drink.alcoholSum;
var alcoholSumType = caller.drink.alcoholSumType;
data.append('alcohol_sum_type', alcoholSumType);
data.append('drink_brand', drinkBrand);
data.append('drink_type', drinkType);
data.append('drink_flavor', drinkFlavor);
data.append('liquid_color', liquidColor);
data.append('liquid_is_transparent', liquidIsTransparent);
data.append('drink_image', drinkImage);
data.append('drink_company', drinkCompany);
data.append('calories_for_100g', caloriesFor100g);
data.append('alcohol_sum', alcoholSum);
$.ajax({
url: 'https://api.myalcoholist.com:8888/drink',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
if (!data.success) {
alert(data.data);
} else {
alert('done');
}
}
});
};
as you can see I set processData and ContentType to false in order to be able to send FormData in jquery ajax call. how can it be done with $http?
$scope.addDrink = function(files) {
// append all what u want.
$http.post('https://api.myalcoholist.com:8888/drink', data, {
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};

How can i get data from FormData in javascript?

I need to read data from FormData? I try to read something like someFormatData["valueName"] but it not working.
options["fileId"] or options["file"] does not work. Also I try options.fileId same result:
function upload(file, fileId, callback) {
var formData = new FormData();
formData.append("file", file);
formData.append("fileID", fileId);
$.ajax({
url: '/url',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
callback(response);
}
});
}
asyncTest("test upload chunk", function() {
var blob = new Blob(["Hello world!"], { type: "text/plain" }),
options = null,
fileID ="someFileID",
response;
jQuery.ajax = function(param) {
options = param; // THIS is FormData object
// how to read fileId and file from here
};
upload(blob, fileID, function (data) {
response = data;
});
options.success({
someProp: 'responseFromServer'
});
setTimeout(function() {
QUnit.equal(options, "dataTosend", "parameters is OK");
QUnit.equal(response["someProp"], "responseFromServer", "Response ok");
start();
},1000);
});
If you take your FormData object you can use a few different methods on it… What you are looking for is
formData.get()
or
formData.getAll()
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Note that the get() method is not fully supported on all browsers.
You can read using this
formData.get('fileId') // to read Id
formData.get('file') // to read the file
Another way to list all entries of a FormData :
for(const entry of formData){
console.log(entry); // Array: ['entryName', 'entryValue']
}

Categories

Resources