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.
Related
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);
}
});
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 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>
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
}
});
});
});
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: '/'
}
}