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!... );
};
Related
How can I turn the results from Script 1, Name, Email, Teamsinto variables I can use in script 2?
I am making an API call to fetch some JSON I then want to use certain values as text in a message I then send to slack.
Example.
$('.Name').html(data.user.name); // Returns John
$('.Email').html(data.user.email); // Returns John#John.com
$('.Teams').html(data.user.teams[0].name); // Returns JohnsTeam
var text = 'Hello my name is $Name + my email is $Email + From $Teams'
Output = Hello my name is John my email is John#John.com From JohnsTeam
Script 1
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Script 2
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
One great solution is to set the variable you get from the response in the HTML5 localstorage as follows:
Inside ur success:
success: function(data) {
localStorage.setItem("urdata",JSON.stringify(data));
}
In the other script, u can retrieve the data like this:
var data = localStorage.getItem("urdata"); data = JSON.parse(data);
I know this is a known issue but I'm having difficulty on fixing my problem. It seems that I don't receive anything from my UI5 Application when I sent an image via FileUploader to my server. I am new to HCP and this is my first time handling XSJS file. I hope you can help me.
UI5.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("sample.controller.View1", {
handleUploadPress : function(oEvent)
{
var fileLoader =this.getView().byId("FileLoader");//XML View
var fileName = fileLoader.getValue();
jQuery.sap.require("sap.ui.commons.MessageBox");
if (fileName === "" )
{
sap.ui.commons.MessageBox.show("Please choose File.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
else
{
var uploadUrl = "https://xxxxxx/services/Sample.xsjs?file_name="+fileName;
var formEle = jQuery.sap.domById("UpdateContact--FileLoader");
var form = $(formEle).find("form")[0] ;
var fd = new FormData(form);
$.ajax({
url: uploadUrl,
type: "GET",
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(data, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
$.ajax({
url: uploadUrl,
type: "POST",
processData :false ,
contentType: false,
data: fd,
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", token);
},
success: function(data, textStatus, XMLHttpRequest)
{
var resptext = XMLHttpRequest.responseText;
jQuery.sap.require("sap.ui.commons.MessageBox");
sap.ui.commons.MessageBox.show(resptext, sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
if(data === "Upload successful"){
sap.ui.commons.MessageBox.show("File uploaded.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
},
error: function(data, textStatus, XMLHttpRequest)
{
sap.ui.commons.MessageBox.show("File could not be uploaded.", sap.ui.commons.MessageBox.Icon.ERROR, "Error");
}
});
}} ) ;
}
}
});
XSJS Service:
$.response.contentType = "text/html";
try
{
var conn = $.hdb.getConnection();
var filename = $.request.parameters.get("file_name");
var headers = $.entity.headers.length;
var pstmt = conn.prepareStatement("INSERT INTO \"XXX_ASSETS\".\"XXX\" VALUES('1',?,'test',CURRENT_USER,CURRENT_TIMESTAMP)");
if($.request.entities.length > 0){
var file_body = $.request.entities[0].body.asArrayBuffer();
pstmt.setBlob(1,file_body);
pstmt.execute();
$.response.setBody("[200]:Upload successful!");
}
else
{
$.response.setBody("No Entries");
}
pstmt.close();
conn.commit();
conn.close();
}
catch(err)
{
if (pstmt !== null)
{
pstmt.close();
}
if (conn !== null)
{
conn.close();
}
$.response.setBody(err.message);
}
}
My code was built based on the tutorials I have found on the internet. Thank You.
A good way to save the image is converting(Base64) and save as blob in HANA table.
Regards
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' }
});
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']
}
Is there any way using Backbone.js and it's model architecture that I can send a formdata object to the server? The problem I'm running into is that everything Backbone sends is encoded as JSON so the formdata object is not properly sent (obviously).
I'm temporarily working around this by making a straight jQuery ajax request and including the formdata object as the data property, but this is less than ideal.
Here is a solution by overriding the sync method, which I use to allow file uploads.
In this case I override the model's sync method, but this can also be the Backbone.sync method.
var FileModel = Backbone.Model.extend({
urlRoot: CMS_ADMIN_URL + '/config/files',
sync: function(method, model, options){
// Post data as FormData object on create to allow file upload
if(method == 'create'){
var formData = new FormData();
// Loop over model attributes and append to formData
_.each(model.attributes, function(value, key){
formData.append(key, value);
});
// Set processData and contentType to false so data is sent as FormData
_.defaults(options || (options = {}), {
data: formData,
processData: false,
contentType: false
});
}
return Backbone.sync.call(this, method, model, options);
}
});
EDIT:
To track upload progress, you can add a xhr option to options:
...
_.defaults(options || (options = {}), {
data: formData,
processData: false,
contentType: false
xhr: function(){
// get the native XmlHttpRequest object
var xhr = $.ajaxSettings.xhr();
// set the onprogress event handler
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
console.log('%d%', (event.loaded / event.total) * 100);
// Trigger progress event on model for view updates
model.trigger('progress', (event.loaded / event.total) * 100);
}
};
// set the onload event handler
xhr.upload.onload = function(){
console.log('complete');
model.trigger('progress', 100);
};
// return the customized object
return xhr;
}
});
...
Just to add an answer to this question, heres how I went about it without having to override the sync:
In my view, I have somethign like:
$('#' + $(e.currentTarget).data('fileTarget')).trigger('click').unbind('change').bind('change', function(){
var form_data = new FormData();
form_data.append('file', $(this)[0].files[0]);
appManager.trigger('user:picture:change', form_data);
});
Which then triggers a function in a controller that does this:
var picture_entity = new appManager.Entities.ProfilePicture();
picture_entity.save(null, {
data: data,
contentType: false,
processData: false,
});
At that point, I'm overriding jQuery's data with my FormData object.
I had a similar requirement and here is what i did :
In View :
var HomeView = Backbone.View.extend({
el: "#template_loader",
initialize: function () {
console.log('Home View Initialized');
},
render: function () {
var inputData = {
cId: cId,
latitude: latitude,
longitude: longitude
};
var data = new FormData();
data.append('data', JSON.stringify(inputData));
that.model.save(data, {
data: data,
processData: false,
cache: false,
contentType: false,
success: function (model, result) {
alert("Success");
},
error: function () {
alert("Error");
}
});
}
});
Hope this helps.
I had the same issue. You can see above the way i solve it.
var $form = $("myFormSelector");
//==> GET MODEL FROM FORM
var model = new MyBackboneModel();
var myData = null;
var ajaxOptions = {};
// Check if it is a multipart request.
if ($form.hasFile()) {
myData = new FormData($form[0]);
ajaxOptions = {
type: "POST",
data: myData,
processData: false,
cache: false,
contentType: false
};
} else {
myData = $form.serializeObject();
}
// Save the model.
model.save(myData, $.extend({}, ajaxOptions, {
success: function(model, data, response) {
//==> INSERT SUCCESS
},
error: function(model, response) {
//==> INSERT ERROR
}
}));
The hasFile is a custom method that extends the JQuery functions.
$.fn.hasFile = function() {
if ($.type(this) === "undefined")
return false;
var hasFile = false;
$.each($(this).find(":file"), function(key, input) {
if ($(input).val().length > 0) {
hasFile = true;
}
});
return hasFile;
};
Just use Backbone.emulateJSON = true;: http://backbonejs.org/#Sync-emulateJSON
will cause the JSON to be serialized under a model parameter, and the request to be made with a application/x-www-form-urlencoded MIME type, as if from an HTML form.
None of the answers worked for me, below is simple and easy solution. By overriding sync method and options.contentType like this:
sync: function(method, model, options) {
options = _.extend({
contentType : 'application/x-www-form-urlencoded;charset=UTF-8'
}, options);
options.data = jQuery.param(model.toJSON());
return Backbone.sync.call(this, method, model, options);
}
A simple one will be, hope this will help someone.
Create a object of Backbone Model:
var importModel = new ImportModel();
Call Save[POST] method of Backbone Model and Pass the FormData Object.
var objFormData = new FormData();
objFormData.append('userfile', files[0]);
importModel.save(objFormData, {
contentType: false,
data: objFormData,
processData: false,
success: function(data, status, xhr) { },
error: function(xhr, statusStr) { }
});