shepard
#1
What is the current method of uploading files to a Node server?
I see plenty of examples using FileTransfer and Transfer - which is the way to go now?
I have had no luck with either on the node end, so if anyone has a Current Example - that would be great!
shepard
#2
Answering my own here in case anyone else can use it.
Upload function in Ionic2 using Native Transfer:
upload() {
const fileTransfer = new Transfer();
var options: any;
options = {
fileKey: 'file',
fileName: 'name.jpg',
headers: {}
}
let filename = "1085.jpg"; // this is a file in the externalDataDirectory
let uploadFile = cordova.file.externalDataDirectory + filename;
console.log("uploadFile: " + uploadFile)
fileTransfer.upload(uploadFile, "https://yourserver.com:3000/upload", options,)
.then((data) => {
console.log("SUCCESS")
}, (err) => {
console.log("FAILURE")
})
}
And in Node:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
console.log("ERROR: "+err);
res.json({error_code:1,err_desc:err});
return;
}
console.log("SUCCESS: ");
res.json({error_code:0,err_desc:null});
})
});