我是NodeJS和loopback的新手。我创建了一个简单的文件上传应用程序环回。应用程序客户端我使用简单的html和Java脚本代码 -
我用ajax调用调用loopback api,这是Java Script完整代码 -
$('#upload-input').on('change', function () {
var files = $(this).get(0).files;
if (files.length > 0) {
// One or more files selected, process the file upload
var form = new FormData();
for (var index = 0; index < files.length; index++) {
var file = files[index];
form.append('Uploded Files', file, file.name);
}
$.ajax({
url: 'api/fileupload/upload',
type: 'POST',
data: form,
processData: false,
contentType: false,
success: function (data) {
console.log('upload successful!');
}
});
}
});
我需要将任何文件作为用户输入并将此文件保存在服务器端的文件夹中。
但我没有在服务器端获取文件对象。在服务器端我创建了一个Loopback api。
可以帮助我们,如何使用loopback api上传文件。
这是我的环回api代码 -
module.exports = function (FileUpload) {var fs = require('fs'); var multer = require('multer');FileUpload.remoteMethod(
'upload', {
http: {
verb: 'post',
},
accepts:
[{
arg: 'req',
type: 'object',
http: {
source: 'req'
}
}, {
arg: 'res',
type: 'object',
http: {
source: 'res'
}
}],
returns: {
arg: 'data',
type: 'string',
root: true
}
}
);
var uploadedFileName = '';
var storage = multer.diskStorage({
destination: function (req, file, cb) {
// checking and creating uploads folder where files will be uploaded
var dirPath = 'client/uploads/'
if (!fs.existsSync(dirPath)) {
var dir = fs.mkdirSync(dirPath);
}
cb(null, dirPath + '/');
},
filename: function (req, file, cb) {
// file will be accessible in `file` variable
console.log("----------its not printing Second Rakesh---");
console.log(file);
var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
var fileName = Date.now() + ext;
uploadedFileName = fileName;
cb(null, fileName);
}
);
FileUpload.upload = function (req, res, callback) {
var upload = multer({
storage: storage
}).array('file', 12);
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
res.json(err);
}
console.log("-------------Rakesh"); // Its Printing Rakesh
res.json(uploadedFileName);
});
}; };