How to display image from selected id - node.js

I'm trying to display the info of the user when I get the id using $routeParams.id, I already displayed the user's info using texts only but how can I display the user's image using img src?
In my controller I did this to get the selected user.
.controller('editbloodrequestCtrl', function($scope,$routeParams, Bloodrequest) {
var app = this;
Bloodrequest.getBloodrequest($routeParams.id).then(function(data) {
if (data.data.success) {
$scope.newLastname = data.data.bloodrequest.lastname;
$scope.newFirstname = data.data.bloodrequest.firstname;
$scope.newImg = data.data.bloodrequest.img;
app.currentUser = data.data.bloodrequest._id;
} else {
app.errorMsg = data.data.message;
}
});
});
Now that I get the users info, I displayed this in my frontend
<label>Lastname:</label>
<input class="form-control" type="text" name="lastname" ng-model="newLastname">
<label>Firstname:</label>
<input class="form-control" type="text" name="firstname" ng-model="newFirstname">
<label>Image:</label>
<img src ="" name="img" ng-model="newImg"> //how can I display the image here?
Sample Documents:
{firstname:"James",lastname:"Reid",img:"random.jpg"}
My output:

No need to bind ng-model to your image, just use the src with the absolute path of the image
<img src ="{{newImg}}" name="img">

No need to bind ng-model to your image, just use the src with the absolute path of the image..ng-model using only input tags.
<img ng-src ="newImg" name="newimg" />

Related

Multer multiple Images Update Form

I've been trying without success to make an update a form that contains multiple inputs for multiple images with Multer.
I managed to make the Create form, I used an upload.files({name: "image1", name: "image2}), etc. The thing is when I created the Update form and when I want to Edit a text field only I get an undefined error since no images files are found.
So I came up with an approach to save the previous (or current image) in and oldImage and assign this in case there is no imagen update.
Here is my code from the controller:
update: (req,res)=>{
let data_games3 = JSON.parse(fs.readFileSync(path.join(__dirname, '../baseDeDatos/data_games3.json')))
req.body.id = req.params.id
req.body.img_1 = req.files ? req.files.img_1[0].filename : req.body.oldImage1
req.body.img_2 = req.files ? req.files.img_2[0].filename : req.body.oldImage2
req.body.img_3 = req.files ? req.files.img_3[0].filename : req.body.oldImage3
req.body.img_4 = req.files ? req.files.img_4[0].filename : req.body.oldImage4
req.body.img_5 = req.files ? req.files.img_5[0].filename : req.body.oldImage5
let gamesUpdate = data_games3.map( games => {
if(games.id == req.body.id){
return games = req.body
}
return games
})
let gameActualizar = JSON.stringify(gamesUpdate, null, 2)
fs.writeFileSync(path.join(__dirname,'../baseDeDatos/data_games3.json'), gameActualizar);
res.redirect('/admin')
}
I can update an image only if the input receives an image. Here is my Edit View trying to store in the input name "oldImage1" a value with current img.
<form action="/admin/edit/<%= gameToEdit.id%>?_method=PUT" method="POST" enctype="multipart/form-data">
<input type="hidden" name="oldImage1" value="<%= gameToEdit.img_1%>" >
<input type="hidden" name="oldImage2" value="<%= gameToEdit.img_2%>" >
<input type="hidden" name="oldImage3" value="<%= gameToEdit.img_3%>" >
<input type="hidden" name="oldImage4" value="<%= gameToEdit.img_4%>" >
<input type="hidden" name="oldImage5" value="<%= gameToEdit.img_5%>" >
Im working with a JSON file as a DB.
The update works great but only if I update all the fields for images too.

Passing a variables value in post request node express

Simple issue - I have a node express app that I want to perform a post request - using request passing the value of a string variable.
I don't want to transfer the name of the variable but its value.
If I just add the name to the query it will pass the actual name.
Looking forward for a solution.
Here is how your html file will look:
<form method='POST' action="/signup">
<b>USERNAME:</b> <input type="text" name="userName" placeholder="yourname">
<br>
<br>
<b>PASSWORD:</b> <input type="password" name="userPass" placeholder="***"><br>
<br>
<b>CONF. PASS.:</b> <input type="password" name="cnfPass" placeholder="***"><br>
<br>
<input type="submit" class = 'btn btn-primary' value="Signup">
</form>
Here is how your js file will look:
app.post('/signup',urlencodedparser,function(req,res){
var uPass=req.body.userPass;
var uName=req.body.userName;
var cnfPass = req.body.cnfPass;
if(uPass!=cnfPass)
res.end('Passwords dont match!')
else
{
con.query("INSERT INTO USERS(name,password) values (?,?)",[uName,uPass])
res.sendfile('user.html')
}
}
)
You can fetch the values of the variables by assigning name to them in the html file.
In this case,
I obtain the input name value with help of 'userName' and 'userPass' fields.

How to reference data from vue,js pug template?

Basically I am trying to make a permalink from an event name. When I get the value from the event name using v-model it works but how do I put the converted permalink back in another input box in pug?
This works:
"P {{message}}",textarea(rows="2") {{message}}
but when i try the following:
input(value="{{message}}"),input(value={{message}}),input(value=#{{message}}),input(value=#{{message}}),input(value=#{message})
Pug does not render it & shows an indent error.
My question is how do I bind or reference data from Vue in input values ?
Pug template:
.col-md-12(style="padding:0px;")
.col-md-2.labelcont
label.labeltext Event Name :
.col-md-10
input(
type="text"
class="form-control"
placeholder="Event Name"
v-model="eventname"
)
.col-md-12(style="padding:0px;")
.col-md-2.labelcont
label.labeltext Permalink :
.col-md-10
textarea(
type="text"
class="form-control"
placeholder="Event Permalink"
) {{eventpermalink}}
Vue.js code:
var basicinfo = new Vue({
el: '#basic',
data: {
eventname: '',
eventpermalink: '',
}
})
basicinfo.$watch('eventname', function (newValue, oldValue) {
basicinfo.eventpermalink = basicinfo.eventname.replace(/[^a-zA-Z0-9 ]/g,'').replace(/ +/g,'-').toLowerCase();
})
You can use the v-bind directive. This way, you can bind any HTML element's attribute to a value whether it's calculated or a reference to your props or data.
In your case, it would be something like this:
input(type="text" class="form-control" placeholder="Event Name"
v-model="eventname" v-bind:value="YOUR-DATA-OR-WHATEVER")
Look the official documentation for further reading:
https://v2.vuejs.org/v2/guide/syntax.html

In Node-RED, how do I upload to a node with the given configuration and retrieve the configuration later?

I am using Node-RED on Bluemix, I want to let the user upload a document, here is the relevant code fragment in a function/template of a flow
<form action="/upload" method="POST">
<h1>Upload PDF</h1>
<input type="file" name="myFile" />
<input type="submit" />
</form>
When I run it, I chose a file and press 'submit', but then comes the message
Cannot POST /upload
Then I went to http://flows.nodered.org/node/node-red-contrib-http-multipart
, in the example there it says
You can upload to a node with the following configuration:
[{ "name": "myFile" }]
and access the files using the following function on the out port of the node
var fields = msg.req.fields;
msg.fields = Object.keys(fields);
var myFile = fields["myFile"][0];
msg.localFilename = myFile.path
...
1) How can I upload a node with the configuration?
2)Once I get the file name, how do I retrieve it to be sent to the next services? -the next service is 'Conversion' - it takes in the file name.
To make it work, you need :
1- a classic http node connected to a html node where you put your form :
<form enctype="multipart/form-data" action="/fileUploaded" method="POST">
<input type="file" name="myFile" />
<input type="submit" />
</form>
2- Then you put your HTTP multipart node with Fields :
[{ "name": "myFile"}]
You link that node to a function node with the following code :
var fields = msg.req.files;
msg.fields = Object.keys(fields);
var myFile = fields["myFile"][0];
var fs = global.get('fs');
var inStr = fs.createReadStream(myFile.path);
var outStr = fs.createWriteStream('/app/public/upload/testUpload');
inStr.pipe(outStr);
msg.localFilename ='/upload/testUpload'
return msg;
You will need to have a folder named "upload" under /app/public/
You will also need 'fs' :
In bluemix-settings.js in functionGlobalContext add fs:require('fs')
In package.json, add "fs":"x.x"
The file will be copied there : /app/public/upload/testUpload
Then we will be able to access it via msg.localFilename in the next node, for example in a HTML page like this :
<html>
<body>
<h1>Job Done</h1>
File uploaded here
</body>
</html>
install multer for node-red and then restart node-red.
npm install node-red-contrib-http-multipart
After you are done with the installation correctly, you will see httpInMultipart Node.
basic html file upload code:
<form action="/upload" enctype="multipart/form-data" method="POST">
<input type="file" name="myFile" />
<input type="submit" />
</form>
httpInMultipart->Function->Http Response Node
Configure the httpInMultipart Node:
method: POST
url: /upload
Fields: [ { "name": "myFile"} ]
In function node Write the following code:
var file = msg.req.files;
var filesize
msg.test=file;
var localFilenamePath = file.myFile[0].path;
var fileSize = file.myFile[0].size;
var response={};
if(msg.test)
{
response.statusCode=0;
response.localFilenamePath=localFilenamePath;
response.fileSize = fileSize;
response.sendMessage="Successful";
}
else
{
response.statusCode=1;
response.sendMessage="Failed";
}
msg.payload=response;
return msg;
And Voila! We are done!

MODX - user profile photo upload

I am trying to allow users to upload photos to their profiles. I am sure I am doing something wrong...
What I currently have configured:
Update Profile Form
[[!UpdateProfile? &useExtended=`1` &preHooks=`user_profile_image` &postHooks=`redirect_profile_update`]]
<div class="update-profile">
<div class="updprof-error">[[+error.message]]</div>
[[+login.update_success:if=`[[+login.update_success]]`:is=`1`:then=`[[%login.profile_updated? &namespace=`login` &topic=`updateprofile`]]`]]
<form class="form" enctype="multipart/form-data" action="[[~[[*id]]]]" method="post">
<input type="hidden" name="nospam:blank" value="" />
<label for="fullname"><i class="icon-user"></i> <strong>[[!%login.fullname? &namespace=`login` &topic=`updateprofile`]]</strong>
<span class="error">[[+error.fullname]]</span>
</label>
<input type="text" name="fullname" id="fullname" value="[[+fullname]]" />
<label for="email"><i class="icon-envelope"></i> <strong>[[!%login.email]]</strong>
<span class="error">[[+error.email]]</span>
</label>
<input type="text" name="email:required:email" id="email" value="[[+email]]" />
<label for="test_field">Test Field
<span class="error">[[+error.custom_field]]</span>
</label>
<input type="text" name="test_field" id="test_field" value="[[+test_field]]" /><br/>
<div class="row clearfix">
<div class="label">Photo<span class="error">[[+fi.error.nomination_file]]</span></div>
<div class="input"><input id="nomination_file" name="nomination_file:required" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div>
</div>
<br class="clear" />
<button class="btn-info btn btn-large" type="submit" name="login-updprof-btn">Update Profile</button>
</form>
</div>
User_profile_image snippet
<?php
// initialize output;
$output = true;
// get the current user name to create the file name as
$userName = $modx->user->get('username');
// valid extensions
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
// create unique path for this form submission
$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// EXAMPLE:
// this would put all file uploads into a new,
// unique folder every day.
// $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
//create file called the user name + pic
$filename = $userName . "pic".'.'.$ext ;
// full path to new file
$myTarget = $target_path . $filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
1) fix quote in this line
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
2) remove all :required in name fields.
3) instead
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
type
$hook->setValue($sf, $uploadpath . $filename);
4) after mkdir($target_path, 0755, true); add
if(file_exists($myTarget) {
chmod($myTarget,0755); //Change the file permissions if allowed
unlink($myTarget); //remove the file
}
For anyone who references this post:
move user_profile_image back to the prehooks like this:
&preHooks=`user_profile_image`
and at line 59 add the missing ")" like this:
if(file_exists($myTarget)) {

Resources