when I try to call the request of both the text and the file I don't get a response. postman just show 200 and nothing is updated to the database.
'use strict';
const Pendingupload = use('App/Models/Pendingupload');
const Helpers = use('Helpers');
class UploadController {
async create({ request, response, auth, session }) {
const { title, description } = request.all();
const validationOptions = {
types: ['image'],
size: '2mb',
extnames: ['png', 'gif']
};
// when call it; there is an error
const avatar = request.file('file', validationOptions);
try {
const Pendinguploads = new Pendingupload();
Pendinguploads.title = title;
Pendinguploads.description = description;
Pendinguploads.user_id = await auth.user.id;
Pendinguploads.image_url = '';
// this is when validation occurs
Pendinguploads.image_url = new Date().getTime + '.' + avatar.subtype;
await avatar.move(Helpers.tmpPath('pendinguploads/pic'));
if (!avatar.moved()) {
return avatar.errors();
}
console.log(Pendinguploads.title);
console.log(Pendinguploads.description);
// })
//await request.multipart.process();
await Pendinguploads.save();
session.flash({ message: 'Your video has been posted!.' });
return response.redirect('upload');
} catch (error) {
session.flash({ uploadError: 'could not upload file' + avatar });
return response.redirect('back');
}
}
}
module.exports = UploadController;
Related
Connection code
till yesterday everything working properly but now it giving the error to connect the json data.
...........................................................................................................................................................................................
class ProductDataStacture with ChangeNotifier {
List<Products> _products = [];
List<Banners> _banners = [];
List<Categories> _category = [];
List<Random> _random = [];
Future<bool> getProducts() async {
String url = 'https://shymee.com';
try {
// http.Response response = await http.get(Uri.parse(url + "/home"),
var response = await http.get(Uri.parse(url + "/home"), headers: {
'Authorization': 'token a867c3c092e8b1195f398ed5ca52dda4e5ff5ed8'
});
var data = json.decode(response.body);
print(data);
List<Products> prod = [];
List<Banners> bann = [];
List<Categories> cate = [];
List<Random> ran = [];
data['products'].forEach((element) {
Products product = Products.fromJson(element);
prod.add(product);
print("this is product ${product}");
});
data['banners'].forEach((element) {
Banners banner = Banners.fromJson(element);
bann.add(banner);
});
data['categories'].forEach((element) {
Categories category = Categories.fromJson(element);
cate.add(category);
});
data['random'].forEach((element) {
Random random = Random.fromJson(element);
ran.add(random);
});
_products = prod;
_banners = bann;
_category = cate;
_random = ran;
return true;
} catch (e) {
print("e getProducts");
print(e);
return false;
}
}
List<Products> get productsList {
return [..._products];
}
List<Banners> get bannersList {
return [..._banners];
}
List<Categories> get categoryList {
return [..._category];
}
List<Random> get randomList {
return [..._random];
}
}
Temporary you can solve this issue with below recommend
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext? context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int
port)=> true;
}
}
enter link description here
But my suggestion is you use valid certificate in server side
On button click I have programmed to call a graphql api which is connected to a Lambda function and the function is pulling data from a dynamodb table. The query does not produce any error, but it doesn't give me any results as well. I have also checked the cloudwatch logs and I dont see any traces of the function being called. Not sure on the careless mistake I am making here.
Here is my api
void findUser() async {
try {
String graphQLDocument = '''query getUserById(\$userId: ID!) {
getUserById(userId: \$id) {
id
name
}
}''';
var operation = Amplify.API.query(
request: GraphQLRequest<String>(
document: graphQLDocument,
variables: {'id': 'USER-14160000000'}));
var response = await operation.response;
var data = response.data;
print('Query result: ' + data);
} on ApiException catch (e) {
print('Query failed: $e');
}
}
Here is my lambda function -
const getUserById = require('./user-queries/getUserById');
exports.handler = async (event) => {
var userId = event.arguments.userId;
var name = event.arguments.name;
var avatarUrl = event.arguments.avatarUrl;
//console.log('Received Event - ', JSON.stringify(event,3));
console.log(userId);
switch(event.info.fieldName) {
case "getUserById":
return getUserById(userId);
}
};
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'ca-central-1'});
async function getUserById(userId) {
const params = {
TableName:"Bol-Table",
KeyConditionExpression: 'pk = :hashKey and sk = :sortKey',
ExpressionAttributeValues: {
':hashKey': userId,
':sortKey': 'USER'
}
};
try {
const Item = await docClient.query(params).promise();
console.log(Item);
return {
id: Item.Items[0].pk,
name: Item.Items[0].details.displayName,
avatarUrl: Item.Items[0].details.avatarUrl,
createdAt: Item.Items[0].details.createdAt,
updatedAt: Item.Items[0].details.updatedAt
};
} catch(err) {
console.log("BOL Error: ", err);
}
}
module.exports = getUserById;
Upon button click I get this
Moving my comment to an answer:
Can you try changing your graphQLDocumnet to
String graphQLDocument = '''query getUserById(\$id: ID!) {
getUserById(userId: \$id) {
id
name
}
}''';
Your variable is $userId and then $id. Try calling it $id in both places like in your variables object.
Your flutter code is working fine but in lambda from the aws is returning blank string "" to not to print anything
hello i wonder to upload images in flutter
i try to use http.MultipartRequest
like this
request.fields["name"] = "$RegisterName";
request.fields["description"] = "$RegisterDescription";
request.fields["caution"] = "$RegisterCaution";
request.fields["price"] = "$RegisterPrice";
request.fields["price_prop"] = "$RegisterPriceProp";
request.fields["user.id"] = "1";
request.fields["lend"] = "$RegisterCategory";
request.fields["category"] = "Digital";
request.fields["place_option"] = "true";
var multipartFile = http.MultipartFile.fromBytes(
'file',
(await rootBundle.load('assets/images/main_1.jpg')).buffer.asUint8List(),
filename: 'test01.jpg',
contentType: MediaType('image', 'jpg'),
);
request.files.add(multipartFile);
var response = await request.send();
if (response.statusCode == 200) print('Upload');
}
but this code is not working
if i use this code, upload only another data
upload things
then json type is this
json type image
i want upload images files ...:(
i use this to send picture with formData
var head = Api().bearerHeader; ////just bearerToken
var request = http.MultipartRequest(
'POST',
Uri.parse(
'https://c.....'));
request.files
.add(await http.MultipartFile.fromPath('TITLEOFFORMDATA', imageFile.path));
request.headers.addAll(head);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
String varo = await response.stream.bytesToString();
}
This is how you can send image to your server with MultipartRequest with http package
try {
final uri = Uri.parse(your_url);
final request = http.MultipartRequest('POST', uri);
final multipartFile =
await http.MultipartFile.fromPath('Image', 'your_path_of_image'); // Image is the parameter name
request.files.add(multipartFile);
request.fields['userId_if_required'] = value;
final response = await request.send();
if (response.statusCode == 200) {
print('success');
} else {
print('Something went wrong');
}
} catch (e) {
print('Something went wrong');
}
How to upload your image to a Django rest API server
this will work for sure, let me know if you have any issues.
Please be sure to add the necessary packages to your pubspec.yaml file
image_picker
http
if there is some I missed please ask me or add it and add as a reply
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
final _picker = ImagePicker();
File? _image;
// use this to send your image
Future<void>uploadImage(filePath) async {
// your token if needed
try{
var headers = {
'Authorization':
'Bearer ' + "token",
};
// your endpoint and request method
var request = http.MultipartRequest(
'POST',
Uri.parse("https://api.imgur.com/3/image"));
request.fields
.addAll({'yourFieldNameKey1': 'yourFieldNameValue1', 'yourFieldNameKey2': 'yourFieldNameValue2'});
request.files.add(await http.MultipartFile.fromPath(
'yourPictureKey', filePath));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}catch(e){
print(e);
}
}
// Use this to pick your image
Future<void> _openImagePicker() async {
try {
var pickedImage = await _picker.pickImage(source: ImageSource.gallery);
if (pickedImage != null) {
setState(() {
_image = File(pickedImage.path);
});
uploadImage(pickedImage.path);
}
} catch (e) {
//print(e);
}
}
I have a method that accept a request like this:
{"token_type":"Bearer",
"expires_in":36000,
"access_token":"blabla",
"refresh_token":"blablbla"}
loginSuccessful (req) {
const jwtDecode = require('jwt-decode')
const decoded = jwtDecode(req.data.access_token)
const role = decoded.scopes[0]
this.toktok = req.data.access_token
localStorage.role = role
localStorage.token = req.data.access_token
localStorage.refresh_token = req.data.refresh_token
},
This method decode the token with jwt-decode and store the informations in localstorage
When I try to test this fonction :
it('Mounting Login successfully Method', () => {
const response = {
data:
{
token_type: 'Bearer',
expires_in: 36000,
access_token: 'dsqdsq',
refresh_token: 'dqsdqs',}
,
}
const wrapper = mount(Login, {
localVue,
sync: false,
})
wrapper.vm.loginSuccessful(response)
expect(localStorage.getItem('token')).toEqual(response.data.access_token)
expect(localStorage.getItem('refresh_token')).toEqual(response.data.refresh_token)
})
I got an error that decoded is undefined
I've created a lambda and assigned it to cognito throw the UI as its custom-message lambda.
Here is the code in typescript:
export const handler = async (event) => {
const trigger = event.triggerSource
const customMessage = cloneDeep(customMessages[trigger])
if (customMessage) {
try {
// inject cognito values to custom message
const codeParameter = event.request.codeParameter
const usernameParameter = event.request.usernameParameter
for (let key in customMessage) {
let text = customMessage[key]
if (codeParameter) {
customMessage[key] = text.replace(/{{codeParameter}}/g, codeParameter)
}
if (usernameParameter) {
customMessage[key] = text.replace(/{{usernameParameter}}/g, usernameParameter)
}
}
// load HTML template
let htmlFile = readFileSync(templateFilePath, { encoding: 'utf8' })
htmlFile = htmlFile.replace(/(\r\n|\n|\r)/gm, '')
const template = handlebars.compile(htmlFile)
const html = template(customMessage)
event.emailMessage = html
event.response.emailSubject = customMessage.title
} catch (err) {
logger.error(err)
return event
}
}
return event
}
Basically it loads an html template file and injects the code-parameters and username.
now the response our signup flow lambda returns is:
{
"message": "InvalidLambdaResponseException",
"details": "Unrecognizable lambda output"
}
I event tried to copy paste AWS example:
exports.handler = (event, context, callback) => {
//
if(event.userPoolId === "theSpecialUserPool") {
// Identify why was this function invoked
if(event.triggerSource === "CustomMessage_SignUp") {
// Ensure that your message contains event.request.codeParameter. This is the placeholder for code that will be sent
event.response.smsMessage = "Welcome to the service. Your confirmation code is " + event.request.codeParameter;
event.response.emailSubject = "Welcome to the service";
event.response.emailMessage = "Thank you for signing up. " + event.request.codeParameter + " is your verification code";
}
// Create custom message for other events
}
// Customize messages for other user pools
// Return to Amazon Cognito
callback(null, event);
};
The response is the same.
Any suggestions?
Thanks
Here is my custom message lambda. It runs on Node 8.10. Maybe you'd like to test/adapt it. I've stripped some other stuff out but it should work fine
exports.handler = function(event, context) {
const cognitoUserPool = 'us-east-1_AAAAAA';
const snsTopicArn = 'arn:aws:sns:us-east-1:9999999999:BBBBBBBBBB';
const baseurl = 'https://company.us-east-1.elasticbeanstalk.com/app';
console.log('Cognito Event:', event);
var AWS = require("aws-sdk");
if(event.userPoolId === cognitoUserPool) {
if(event.triggerSource === "CustomMessage_SignUp") {
event.response.emailSubject = "Welcome to Company";
event.response.emailMessage = "Hello etc";
context.done(null, event);
}
if(event.triggerSource === "CustomMessage_ResendCode") {
event.response.emailSubject = "Welcome to Company";
event.response.emailMessage = "Some other message etc";
context.done(null, event);
}
if(event.triggerSource === "CustomMessage_ForgotPassword") {
event.response.emailSubject = "Your password reset";
event.response.emailMessage = "Some other message again etc";
context.done(null, event);
}
// Other event types can go here
} else {
context.done(null, event);
}
};