I've a angular function for to upload file to web api
$scope.uploadFile = function () {
var file = $scope.file;
console.log("file: " + file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", uri);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
$scope.progressVisible = true;
xhr.send(file);
}
function uploadProgress(evt) {
$scope.$apply(function () {
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
}
})
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
$scope.$apply(function () {
$scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
The code is available here http://jsfiddle.net/vishalvasani/4hqVu/
I need a web api controller to manage file post, how can I read it?
Is it possible to use PostValue instead of task async?
Server side I get the file, read content, query a database and return JSON response
Thanks
Related
I am using TinyMCE 5.7 and it handles uploading images well. However when an image is pasted from the clipboard (ex: Snipping Tool) it gets pasted as data which is not desired. I can use the setting paste_data_images to block pasting data images but I would prefer that it convert the data into an upload request like normal image upload process. Is there a way to intercept the paste and do the upload? I am using both the image and paste plugins. Thanks
Eventually I figured out how to write my own paste function. First, in the TinyMCE config:
setup: function (editor) {
editor.on('paste', function (e) {
var imageBlob = retrieveImageFromClipboardAsBlob(e);
if (!imageBlob) {
return;
}
e.preventDefault();
uploadFile(imageBlob, function (response) {
if ('location' in response) {
if (editor) {
// console.log('upload completed', response);
editor.insertContent('<img src="' + response.location + '" />');
} else {
console.log('Tinymce editor not found!');
}
}
});
});
}
Then the routine to decode the pasted info:
function retrieveImageFromClipboardAsBlob(pasteEvent) {
if (pasteEvent.clipboardData === false) {
return false;
}
var items = pasteEvent.clipboardData.items;
if (items === undefined) {
return false;
}
for (var i = 0; i < items.length; i++) {
// Only paste if image is only choice
if (items[i].type.indexOf("image") === -1) {
return false;
}
// Retrieve image on clipboard as blob
var blob = items[i].getAsFile();
// load image if there is a pasted image
if (blob !== null) {
const reader = new FileReader();
reader.onload = function(e) {
// console.log('result', e.target.result);
};
reader.readAsDataURL(blob);
return blob;
}
}
return false;
}
and a routine to upload the file
function uploadFile(file, callback) {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percentComplete = (e.loaded / e.total) * 100;
console.log("Uploaded: " + percentComplete + "%");
};
xhr.onload = function () {
if (xhr.status !== 200) {
alert("Error! Upload failed " + xhr.response);
}
if (callback) {
callback(JSON.parse(xhr.response));
}
};
xhr.onerror = function () {
alert("Error! Upload failed. Can not connect to server.");
};
xhr.open("POST", "/upload/tinymce", true);
var data = new FormData();
data.append('file', file);
xhr.send(data);
}
I'm new to the flutter, I start to create a simple messenger app using flutter and flutter stream to handle API call for get message content.
also created the message controller to update and refresh the message list
class MessageService {
Client httpClient = Client();
List<MessageModal> _messageList = [];
Future<AppConfig> _getApiURL() async {
final config = await AppConfig.forEnvironment('dev');
return config;
}
Future<List<MessageModal>> getMessageThread(
String senderId, String receiverId) async {
var config = await _getApiURL();
var url = config.baseUrl + "message/history";
final response = await httpClient.post(url,
headers: {"content-type": "application/json"},
body: json.encode({
"senderId": senderId,
"receiverId": receiverId,
}));
if (response.statusCode == 200) {
_messageList = messageListFromJson(response.body);
} else {
_messageList = [];
}
return _messageList;
}
}
Here is the message service class for fetch API data
class MessageService {
Client httpClient = Client();
List<MessageModal> _messageList = [];
Future<AppConfig> _getApiURL() async {
final config = await AppConfig.forEnvironment('dev');
return config;
}
Future<List<MessageModal>> getMessageThread(
String senderId, String receiverId) async {
var config = await _getApiURL();
var url = config.baseUrl + "message/history";
final response = await httpClient.post(url,
headers: {"content-type": "application/json"},
body: json.encode({
"senderId": senderId,
"receiverId": receiverId,
}));
if (response.statusCode == 200) {
_messageList = messageListFromJson(response.body);
} else {
_messageList = [];
}
return _messageList;
}
}
Here is the ui preview to create the message list preview
StreamBuilder<List<MessageModal>> _buildStreamBuilder() {
return StreamBuilder<List<MessageModal>>(
// stream: _messageService.getMessageThread("UID1", "UID2").asStream(),
stream: streamController.counter,
initialData: _messageList,
builder:
(BuildContext context, AsyncSnapshot<List<MessageModal>> snapshot) {
print(snapshot.data);
if (snapshot.hasError) {
print(snapshot.error);
return Center(
child: Text("Something went wrong!"),
);
} else if (snapshot.hasData) {
List<MessageModal> messages = snapshot.data;
return _buildMessageHistory(messages);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
I need to do the messages update and also keep updating (send the API call and fetch data to stream) the message preview. can anybody help me on this one.
It's been a while since this question was originally asked. Since then the Stream Chat Flutter support has improved a lot. Implementing what this question asks is now really easy, with varying levels of customisability.
Pre-built UI widgets package : https://pub.dev/packages/stream_chat_flutter
This package is plug and play to add chat support, with a lot of customisability options.
If you want more control: https://pub.dev/packages/stream_chat_flutter_core
This package provides convenient builders to enable you to build your own UI components. It does the heavy lifting for you but will require more implementation on your side.
If you want low level control:
https://pub.dev/packages/stream_chat
Check out the tutorial for an easy getting started guide: https://getstream.io/chat/flutter/tutorial/
See here for awesome Stream examples of what you can build: https://github.com/GetStream/flutter-samples
Video tutorials: https://www.youtube.com/playlist?list=PLNBhvhkAJG6t-BxkRAnSqa67lm5C1mpKk
So I'm trying to make a google action using Dialogflow that requires an external API. I've always used jQuery .getJSON() to make API calls, so I had no idea how to do this. After searching this up online, I found a way to do this using vanilla javascript (I also tested the way on my website and it worked fine). The code for that is below:
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "https://translate.yandex.net/api/v1.5/tr.json/translate?lang=en-es&key=trnsl.1.1.20190105T052356Z.7f8f950adbfaa46e.9bb53211cb35a84da9ce6ef4b30649c6119514a4&text=eat", true);
xmlhttp.send();
}
The code worked fine on my website, but as soon as I added it to the Dialogflow, it would give me the error
XMLHttpRequest is not defined
Obviously that happened because I never defined it (using var), except it worked without me doing anything. So then, I tried adding this line
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
to the code, and it stopped giving me the error (because I defined XMLHttpRequest). But then, my code wouldn't work.
TL;DR: How can I make an external API call using Dialogflow fulfillment?
You can use https. But make sure that you upgrade to Blaze Pay(or any other plans) to make external API calls, else you will receive an error such as
Error:
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions.
Code to make external api call,
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
"use strict";
const functions = require("firebase-functions");
const { WebhookClient } = require("dialogflow-fulfillment");
const { Card, Suggestion } = require("dialogflow-fulfillment");
const https = require("https");
process.env.DEBUG = "dialogflow:debug"; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(
(request, response) => {
const agent = new WebhookClient({ request, response });
console.log(
"Dialogflow Request headers: " + JSON.stringify(request.headers)
);
console.log("Dialogflow Request body: " + JSON.stringify(request.body));
function getWeather() {
return weatherAPI()
.then(chat => {
agent.add(chat);
})
.catch(() => {
agent.add(`I'm sorry.`);
});
}
function weatherAPI() {
const url =
"https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
return new Promise((resolve, reject) => {
https.get(url, function(resp) {
var json = "";
resp.on("data", function(chunk) {
console.log("received JSON response: " + chunk);
json += chunk;
});
resp.on("end", function() {
let jsonData = JSON.parse(json);
let chat = "The weather is " + jsonData.weather[0].description;
resolve(chat);
});
});
});
}
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
let intentMap = new Map();
intentMap.set("Default Welcome Intent", welcome);
intentMap.set("Default Fallback Intent", fallback);
intentMap.set("Weather Intent", getWeather);
agent.handleRequest(intentMap);
}
);
This article is a diamond! It really helped to clarify what's going on and what's required in Dialogflow fullfilments.
A small suggestion is to gracefully catch the error in the connection to the webservice:
function weatherAPI() {
const url = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
return new Promise((resolve, reject) => {
https.get(url, function(resp) {
var json = "";
resp.on("data", function(chunk) {
console.log("received JSON response: " + chunk);
json += chunk;
});
resp.on("end", function() {
let jsonData = JSON.parse(json);
let chat = "The weather is " + jsonData.weather[0].description;
resolve(chat);
});
}).on("error", (err) => {
reject("Error: " + err.message);
});
});
}
Trying to load JSON file with Safari Extension.
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI +'js/data.json', true);
It gives an error "Cross origin requests are only supported for HTTP."
For example it is possible with Chrome Extenison
var xhr = new XMLHttpRequest();
xhr.open("GET", chrome.extension.getURL('/js/data.json'), true);
There you need to specify it in manifest
"web_accessible_resources": ["/js/data.json"]
Is there a similar way in Safari?
EDIT
Found a solution
It is possible through Global page
global.html
function handleMessage(event) {
if (event.name === "requestParagraphs") {
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI + 'js/data.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var articlesJSON = JSON.parse(xhr.responseText);
event.target.page.dispatchMessage('paragraphs', articlesJSON);
}
};
xhr.send();
}
}
safari.application.addEventListener("message", handleMessage, false);
injected.js
function handleMessage(msgEvent) {
var messageName = msgEvent.name;
var messageData = msgEvent.message;
if (messageName === "paragraphs") {
// ...
}
}
safari.self.addEventListener("message", handleMessage, false); // Listen response
safari.self.tab.dispatchMessage('requestParagraphs'); // Call global page
I am developing a chrome extension and I have an iframe which I use in my extension. This is what I do with my iframe
"When I drag and drop a image to my iframe I handle the drop event in one of the content scripts and pass that function call my extension code. There I create a xmlhttprequest object and then send the URL of the image to a php file in my server."
This is what is happening. I get a readyState of "4" but there is no POST request going out of my browser. I checked with the "NETWORK" tab in the browser but there is no POST request going out of the browser (I have listed my site in the permissions section of the manifest file).
This is my code --.>
JScript.js(One of the content scripts )
drop: function(event, ui) {
var imgurl=$(ui.draggable).attr('src');
imgurl="IMGURL="+imgurl;
_post("www.somedomain.come/testing.php",imgurl,function(result){ alert("success")});
}
This is my proxy in the same content script-->
_post = function(url, data, callback)
{
console.log("sending post");
chrome.extension.sendRequest({
msgType:'post',
data: data,
url:url
}, function(response){
alert(response);
});
}
This my OnRequest function handler in background.html -->
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
if (request.msgType === 'post') {
alert("Now in OnRequest function");
// console.log("Now in Onrequest Function");
alert("Url: "+request.url + "\n Data : "+ request.data);
ajaxcallingfunction(request);
alert("completed the ajax call");
sendResponse("success");
}
});
var ajaxcallingfunction = function(request){
var xhr = new XMLHttpRequest();
xhr.open("POST",request.url, false);
xhr.onreadystatechange = function(){
alert(xhr.readyState);
if (xhr.readyState == 4) {
alert(xhr.readyState);
}
}
xhr.send(request.data);
alert("after xhr call");
};
You have http:// in front of your url, right?
xhr.readyState doesn't tell much, it just means that it is done. Check out what's inside xhr.status, it would contain error code. If everything is ok it should be 200:
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
alert(xhr.status);
}
}