javascript - Issue with ajax file upload (Node.js, express, jQuery) -
i struggling file upload script working. using node/express backend jquery firing off ajax request.
markup:
<input id="audio" type="file" name="audio">
front end js:
var formdata = new formdata(); formdata.append("audio", e.data.audio, 'testname'); $.ajax({ url: 'api/upload', data: formdata, cache: false, contenttype: false, processdata: false, type: 'post', success: function(data){ alert(data); } });
using custom written module executes next , places e.data.audio
if(has('filereader')){ homecoming this.$input[0].files[0] || ''; }
when select little sound file upload , submit, e.data.audio has next value @ point set ajax function argument object:
lack of streetcred means need set images on imgur http://i.imgur.com/mz5mnxr.png
after request sent using files property of request object (req.files) access file, in order save it.
exports.upload = function(){ homecoming function(req, res){ console.log(req.files); if (req.files && req.files.audio){ var file = req.files.audio; fs.readfile(file.path, function(err, data){ if (err){ res.send(err); } var newpath = __dirname + 'public/audio'; fs.writefile(newpath, data, function(err){ if (err){ res.send(err); }else{ res.send(true); } }); }) }else{ } } };
however issue path seems clients local path.
lack of streetcred means need set images on imgur http://i.imgur.com/9e82xv1.png
ive done fair amount of googling , cant seem find along same lines. missing basic , need point me in right direction.
file.path
path temporary file created on server holds uploaded file data, it's not path of file uploader's system.
on unrelated note, __dirname
not include trailing slash you'll want this:
var newpath = __dirname + '/public/audio';
instead of:
var newpath = __dirname + 'public/audio';
also should utilize fs.rename
move file instead of reading whole file memory , writing out again. example:
var file = req.files.audio; fs.rename(file.path, __dirname + '/public/audio', function(err) { res.send(err ? err : true); });
javascript jquery ajax node.js file-upload
No comments:
Post a Comment