Skip to content

Instantly share code, notes, and snippets.

@Erichain
Last active March 3, 2017 10:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Erichain/911c0d4a5f31e38b744b03cd65885ce6 to your computer and use it in GitHub Desktop.
Save Erichain/911c0d4a5f31e38b744b03cd65885ce6 to your computer and use it in GitHub Desktop.
Use ionic and express.js to upload files
app.controller(['$cordovaFileTransfer', function ( $cordovaFileTransfer ) {
// 一定要将代码放在事件监听中
// 表示设备准备好了之后才能执行里面的代码
document.addEventListener('deviceready', function () {
var uploadOptions = new FileUploadOptions(),
server = 'your_server_api',
imgPath = 'your_img_path';
// 注意此处设置的fileKey,Express服务端中也需要这个
uploadOptions.fileKey = 'file';
uploadOptions.fileName = imgPath.substr(imgPath.lastIndexOf('/') + 1);
uploadOptions.mimeType = 'image/jpeg';
uploadOptions.chunkedMode = false;
$cordovaFileTransfer.upload( server, imgPath, uploadOptions )
.then(function ( result ) {
// 上传成功
}, function ( error ) {
// 上传失败
}, function ( progress ) {
// 上传进度
});
}, false);
}]);
var router = require('express').Router(),
uploadPhoto = require('/modules/path/server_upload').uploadFile;
router.all('/photo_upload', function ( req, res ) {
uploadFile(req, res);
});
var multer = require('multer'),
storage = multer.diskStorage({
destination: function ( req, file, callback ) {
// 注意,此处的uploads目录是从项目的根目录开始寻找
// 如果没有的话,需要手动新建此文件夹
callback(null, './uploads');
},
// multer不会自动添加文件后缀名,需要手动添加
filename: function ( req, file, callback ) {
callback(null, file.fieldname + '-' + Date.now() + '.' + file.mimetype.split('/')[1]);
}
}),
// single里的字符串必须设置为与客户端设置的fileKey一致
upload = multer({
storage: storage,
limits: 1000000
}).single('file');
// upload photo
function uploadFile( req, res ) {
upload(req, res, function ( error ) {
if ( error ) {
console.error(JSON.stringify(error));
return res.end('Error uploading file.');
}
console.log('Success!');
res.end('File is uploaded');
});
}
exports.uploadFile = uploadFile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment