以下是我的代码。我在MVC模板中使用express。
我正在使用邮递员以表格数据模式测试此路线。目录设为public/images/avatar/1510932719839-BHqhegjFMc3Qf/
,只有我上传的文件(图片)不在其中。我没有收到任何错误,没有任何问题,也没有任何崩溃。
let routes = require('./routes')(app, dbPool, passport, redisClient);
app.use(express.static('public'));
app.get("*", function (req, res) {
fs.createReadStream("./public/index.html").pipe(res);
});
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 10000
}));
app.use(bodyParser.json());
app.listen(80);
let FileUploadController =
require('./../controllers/fileUploadController');
module.exports = function (app, dbPool, passport, redisClient) {
let fileUploadController = new FileUploadController(dbPool,
redisClient);
let uploadRouteImage = "/api/upload/image/";
let uploadRouteFile = "/api/upload/file/";
app.route(uploadRouteImage + "avatar")
.post(fileUploadController.imageUploaderAvatar );
}
let cast = require('model-generator').Cast;
let jwt = require('json-web-token');
let PhotoUploadService =
require('./../services/fileUpload/photoUploadService');
let coreFunctions = require('./../core_classes/CoreFunctions');
let photoUploadService,
pdfUploadService;
module.exports = class FileUploadController {
constructor(dbPool, redisClient) {
photoUploadService = new PhotoUploadService(dbPool, redisClient);
pdfUploadService = new PdfUploadService(dbPool, redisClient);
}
imageUploaderAvatar(req, res) {
let promises = [
coreFunctions.randomFileNameGenerator() //return:
1510932719839-BHqhegjFMc3Qf
];
let promisesResults;
Promise.all(promises)
.then(result => {
photoUploadService.storage(result[0], 'avatar', 255, 255)
.then(storage => {
photoUploadService.upload(req.file, storage)
.then(result => {
res.status(200).json({status: "Success"})
})
.catch(error => {
res.status(400).json({error: "Something
went wrong."})
})
})
.catch(error => {
console.log(error);
res.status(400).json({error: "Something went
wrong."})
})
})
.catch(error => {
console.log(error);
res.status(400).json({error: error})
});
}
let multer = require('multer');
let path = require('path');
let imager = require('multer-imager');
module.exports = class PhotoUploadService {
constructor(dbPool, redisClient) {
this.fileUploadRepository = new FileUploadRepository(dbPool);
this.redisClient = redisClient;
}
storage(fileName, type, width = 255, height = 255) {
return new Promise((resolve, reject) => {
let location = `./public/images/${type}/${fileName}/`;
resolve(
imager({
bucket: 'bucket-name',
location: location,
dirname: 'avatar',
accessKeyId: 'string',
region: 'us-east-1',
acl: 'public-read',
secretAccessKey: 'string',
filename: fileName,
gm: {
width: width,
height: height,
format: 'jpg'
}
}) ) })
}
upload(fieldname, storage) {
return new Promise((resolve, reject) => {
multer({
storage: storage,
limits: {fileSize: 1500000000000}
}).single(fieldname);
resolve(true);
})
}
}