I am making an app using Ember as my front-end and Hapi as my back-end. I have a pseudo-form that, when submitted, simply makes a post to my Hapi server to upload a file and waits for a response telling the front-end where it was uploaded to. I say "pseudo-form" because the form does not have an action
attribute, but rather the submit click is handled to send the ajax request.
It seems that for some reason, simply calling fs.createWriteStream
in the server will cause the client's browser to refresh after the AJAX request finishes, and this won't work for what I'm trying to accomplish. Does anyone know why this might be the case?
Here is my Hapi server:
var Hapi = require( 'hapi' );
var fs = require( 'fs-extra' );
var uploads_directory = "/uploads/";
var server = new Hapi.Server();
server.connection( { host: 'localhost', port: 3000 } );
// Add the server routes
server.route( {
method: 'GET',
path: '/hello',
handler: function( request, reply ) {
return reply( 'hello world' );
}
} );
server.route( {
method: 'POST',
path: '/submit',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
handler: function( request, reply ) {
console.log( "Made it in the handler" );
var data = request.payload;
if( data.file ) {
console.log( "There is a file" );
var name = data.file.hapi.filename;
console.log( "Named " + name );
fs.ensureDirSync( __dirname + uploads_directory );
var path = __dirname + uploads_directory + name;
var file = fs.createWriteStream( path );
file.on( 'error', function( err ) {
console.error( err );
} );
data.file.pipe( file );
data.file.on( 'end', function( err ) {
reply( path );
} );
} else {
console.log( "There is no file" );
reply( "None" );
}
}
}
} );
server.start( function() {
console.log( 'Server running at:', server.info.uri );
} );
The line that causes the issue is var file = fs.createWriteStream( path );
If I simply reply( path ');
here and then return from the function, it does not cause the page refresh on my client.
Here is my call to AJAX, where "fd" is a FormData
instance holding the file to be uploaded:
Ember.$.ajax( {
type: "POST",
url: "/submit",
data: fd,
success: function( image_path ) {
debugger;
}
} );
Aucun commentaire:
Enregistrer un commentaire