How to find payload in hapi - node.js

I have the following route in hapijs server. And i am trying to create a new file using ajax.
{
method: 'POST',
path: '/create',
config : {
payload:{
maxBytes: 10*1024*1024,
output:'stream',
parse: true,
allow: 'multipart/form-data'
},
handler: function (request, reply) {
var data = request.payload;
if (data.file) { // undefined always
var name = data.file.hapi.filename;
var path = writePath + '/' + name;
var file = fs.createWriteStream(path);
file.on('error', reply);
data.file.pipe(file);
data.file.on('end', function (err) {
reply({
filename: data.file.hapi.filename,
headers: data.file.hapi.headers
});
});
} else reply(boom.badRequest('No file found. Please try again.'));
}
}
The above code always give data.file as undefined. Anything am i missing?
In hapi documentation http://hapijs.com/api#requests, when output is stream
'stream' - the incoming payload is made available via a
Stream.Readable interface. If the payload is 'multipart/form-data' and
parse is true, fields values are presented as text while files are
provided as streams. File streams from a 'multipart/form-data' upload
will also have a property hapi containing filename and headers
properties.
html code :
<form enctype="multipart/form-data" action="/create" method="post">
<input type="file" id="UniqueFileImporter"/>
<input type="submit"/>
</form>
of course there is no js code, as i simply need to submit the form after selecting a file from system

thanks to Matt Harrison for pointing out mistake, i was missing attribute name in file inputer.
html should be
<form enctype="multipart/form-data" action="/create" method="post">
<input type="file" name="file" id="UniqueFileImporter"/>
<input type="submit"/>
</form>

Related

Problems with Post req (NodeJs/Express) - sending an empty object?

I am having some issues with a Post request. I am trying to post a js object, the http request works but it doesnt seems to get the values form the input fields, it posts instead an empty object! I have tried everything cant seems to find the error!
app.js
function addPoem() {
event.preventDefault();
let title = document.getElementById("titleInput").value;
let author = document.getElementById("authorInput").value;
let text = document.getElementById("textInput").value;
let newPoem = {
id: 8,
title: title,
author: author,
text: text,
};
makeRequest("/poems/", "post", newPoem);
}
async function makeRequest(url, reqMethod, body) {
const response = await fetch(url, {
//headers = { "Content-Type": "application/json" },
method: reqMethod,
body: JSON.stringify(body),
});
console.log(response);
const data = await response.json();
console.log(data);
}
index.html
<form method="post" action="/poems">
<h1>Send us your poem!</h1>
<input type="text" requirede name="title" id="titleInput"> <br>
<input type="text" required name="author" id="authorInput"> <br>
<br>
<input type="text" required name="text" id="textInput" style="width:500px;height:500px">
<br>
<button type="submit" onclick="addPoem()">Send</button>
</form>
server.js
// Post a poem
app.post("/poems", (req, res, next) => {
allPoems.push(req.body);
res.json({ status: "A new poem has been posted!" });
});
I think your method should work, because you post directly from the server.js method
But if you yang to use the function in app.js use this
form method="post" action="/poems"
To
form method="post" onsubmit="addPoem()"

How to upload a XML file using HTTPS upload (REST)

When I submit a simple form like this with a file attached:
<form name="bilupload" action="https://localhost:3000/finn/import/fileimport" method="post" enctype="multipart/form-data">
fil: <input TYPE="FILE" NAME="fil" size="30">
<input type="submit" value="Send">
</form>
How does it send the file internally? Is the file sent as part of the HTTP body as data? In the headers of this request, I don't see anything related to the name of the file.
I just would like the know the internal workings of the HTTP when sending a file.
I try this:
HTTP.post("https://localhost:3000/finn/import/fileimport", {
headers: {'Content-Type': 'multipart/form-data',
'Content-Disposition': 'form-data',
name: "fil",
filename:"finn.xml"
},
data: XMLDate
}, function (err, result) {
if (err) {
console.log("err", err);
} else {
console.log("result", result);
}
});

How to upload image with Strapi.io and AngularJS?

I have a type of http.post that has to be via Curl, type this example:
curl -X POST -F 'files=#/path/to/pictures/avatar.jpg&refId=5a993616b8e66660e8baf45c&ref=user&source=users-permissions&field=avatar' http://localhost:1337/upload
As you can see is sending image to a specific field. This curl is represented by this JSON:
{
"files": "...", // Buffer or stream of file(s)
"path": "user/avatar", // Uploading folder of file(s).
"refId": "5a993616b8e66660e8baf45c", // User's Id.
"ref": "user", // Model name.
"source": "users-permissions", // Plugin name.
"field": "avatar" // Field name in the User model.
}
Like this documentation: https://strapi.io/documentation/3.x.x/guides/upload.html#examples
Well, doing it this way in Angular:
Creating an input in the html of my component:
<input type="file" name="file" (change)="onFileSelected($event)">
Creating your event:
onFileSelected(event) {
console.log(event);
}
I have several results among them the file with:
files: FileList
0: File(58456)
lastModified: 1542844204930
lastModifiedDate: Wed Nov 21 2018 21:50:04 GMT-0200 (Horário de Verão de Brasília) {}
name: "8.jpg"
size: 58456
type: "image/jpeg"
webkitRelativePath: ""
Ok, but make any tests using Postman to understand better who I can do this, return me "true", but nothing happens in my database:
How can I use the curl, shown at the beginning, with the post-Angled method, or even Postman (which would have a clearer idea), since I already have all the data I need?
Here is how to did it with jQuery, you will just have to adapte it with Angular.
You also will have to add your ref attributes to make the relation with your user.
<form method="post">
<input type="file" name="files" id="files">
<input type="submit" name="" value="Submit">
</form>
<script type="text/javascript">
$('form').on('submit', function (e) {
e.preventDefault();
var data = new FormData();
$.each($('#files')[0].files, function(i, file) {
data.append('files', file);
});
$.ajax({
url: '/upload',
data: data,
contentType: false,
processData: false,
method: 'POST',
success: function(data){
alert(data);
}
});
});
</script>

Not able to upload image on server using Api in meteor

I am using 'nimble:restivus' package of meteor to create a api for uploading the image.
HTML:
<form id="upload" onSubmit="upload()">
<input type="file" id="avatar" name="avatar" />
<input type="text" id="fname" name="fname" />
<button type="submit">Submit</button>
</form>
Ajax Request:
var file_data = $("#avatar").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append("userId", '8NrAn4sR3bKmXi84u');
form_data.append("fileName", file_data.name);
$.ajax({
url: "http://localhost:3000/api/v1/uploadImages/",
cache: false,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
processData: false,
data: form_data,
type: 'POST'
});
Api Code:
var Api = new Restivus({
version: 'v1',
useDefaultAuth: true
});
Api.addRoute('uploadImages', { authRequired: false }, {
post: function(){
console.log("=====> UPLOAD IMAGES API <======");
console.log("this.bodyParams -> ",this.bodyParams)
return true;
}
});
Server side Response(API):
Please check attached image for console output on server side--
When i submitting the form as POST, not able to get the image on server side. As i received body-params but when i tried to get image as this.bodyParams.file, it returns undefined.
Please guide me how i can image on server side after submitting the form.
Thanks.

Upload image to server - Hapi.js

I'm trying to upload an image to my server, and then save it to MongoDB. I'm using Hapi.js, React.js, Flux and Mongoose.
What I get in the payload is the following. Is this the path to the image?
{ path: '/var/folders/rl/6ygb2kgx7xnbkhnrpdxlbcl80000gp/T/1430991015360-27136-94254437ff20c8ce',
bytes: 68 }
Sorry if this question is a bit long, but I wanted to include all the steps.
Here is the form:
<form method="POST" onSubmit={this.handleSubmit} enctype='multipart/form-data'>
<input type="file" name="newImage" ref="image" accept="image/*" />
<input type="submit" value="Share image" />
</form>
Here is the handleSubmit:
handleSubmit: function(e){
e.preventDefault();
var image = React.findDOMNode(this.refs.image).value;
var data = {
image: image
};
ActionCreators.saveImage(data);
},
Then, ActionCreators passes it on to APIUtils:
saveImage: function(data){
APIUtils.saveImage(data);
}
Finally, APIUtils sends the image as an AJAX request to the server:
saveImage: function(data){
Request.post('/api/image')
.send(data)
.end(function(err,res){
// do something with the response later on
});
}
Now, I'm trying to get access to this image on the server. Server.js:
{
path: '/api/image',
method: ['POST'],
config: {
payload: {
output:'file',
maxBytes:209715200,
parse: false
},
auth: {
strategy: 'session',
mode: 'try'
},
handler: function(request,reply){
var payload = request.payload;
console.log('payload: ', payload);
},
plugins: {
'hapi-auth-cookie': {
reddirectTo: '/'
}
}

Resources