I'm new to node.js. I need to create and submit a form with a file to a url.
What is the way to do it?
I'm not able to find clear information about it.
I don't want to use form-data to do this simple thing moreover it requires a series of dependent modules.
I've used nodejs-websocket module to create a server which listens from browser clients.
You can try using express/multer for handling file upload in the server side. Its much simple.
Use an AJAX request on the client side to upload the file when the button is clicked.
<form role="form" enctype="multipart/form-data" >
.....
<input type="file"/>
<form />
$('#upload_button_id').click(function (event) {
$('#form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
type:'post,'
url: '/url/fileupload/', //the URL to your node.js server that has data
dataType: 'json',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
//file was uploaded successfuly
alert(response);
},
error: function(){
//Something went wrong
}
});
});
});
Related
I want to add a submit form on a site with domain name source.com and when the user submits the button I want to redirect him to a site with domain name target.com. The app hosted at target.com has a backend at backend.target.com and a frontend at frontend.target.com.
On the source.com I have :
<form action="https://backend.target.com" method="POST">
<input type="text" id="textId" name="textName">
<input type="submit" value="Submit">
</form>
My problem is, that I want somehow to redirect the user on frontend after receiving the post request at backend. How can I achieve that ?
I think it would be better to have a service that does that. Submit the form though a REST service (Look here), wait for the response, and based on that response decide where to navigate the client.
Your client can be something like
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request Example' })
};
fetch('http://someapi', requestOptions)
.then(response => //redirect to whereever)
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>
I have a rest server running locally and a front end server running locally aswell. The rest server uses restify and session-cookie with passportjs. This all seems to be working fine as im using Postman app to test the API where cookies are being found and saved:
Postman app image
But when i use ajax on my front end app to login, i do not receive the cookie. Or at least it does not seem to save. This is the ajax code:
$("form#login-form").submit(function(){
var data ={
email: $(this).find("input[name='email']").val(),
password: $(this).find("input[name='password']").val()
};
var data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: URL + "/login",
data: data,
contentType: "application/json",
dataType: "json",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
if(data.error){
console.log("logged in error:" + data.error);
}
else {
console.log("logged in:" + data.LoggedIn);
window.location.replace("/");
}
}
});
But the front end acts like it does log me in with each page displaying the right user info and logging out works perfectly too, but i cannot find a stored session for the page anywhere in chrome or firefox dev tools.
What could be causing this?
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.
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>