Я использую Uppy для загрузки файлов с помощью перетаскивания, но, как мы все знаем, Uppy не заботится о фактической загрузке файлов на сервер. Поэтому я использую Multer в качестве моего сервера для загрузки файлов на мой сервер. Хотя я столкнулся с загадкой. Когда я загружаю файл, мне нужно изменить имя файла на текущую дату плюс расширение. Но когда я консольный журнал, он выходит "неопределено".
функции. js
let path = require('path');
const multer = require('multer');
let myUploadFunction = function _multerFunction(req, res, filePath){
let newFileName;
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, filePath);
},
filename: function (req, file, callback) {
console.log("Storage Function " , file);
callback(null, newFileName = Date.now() + path.extname(file.originalname));
getNewFileName(newFileName); // Trying to pass this function to the upload.js route but it comes back undefined.
}
});
let upload = multer({ storage : storage}).any();
upload(req, res, function (err) {
if(err) {
return res.end("Error uploading file. "+ err);
}
console.log("New File Name " + newFileName); // This console log does print the new file name
});
};
let getNewFileName = function getNewCreatedFileName(fileName){
return fileName;
};
module.exports.myUploadFunction = myUploadFunction;
module.exports.getNewFileName = getNewFileName;
загрузить. js
let express = require('express');
let router = express.Router();
let upload = require('../functions/functions');
//const mysql_connection = require('../db'); // Database connection file.
/* POST upload route. */
router.post('/', function(req, res, next) {
upload.myUploadFunction(req, res, 'public/images', 'File is upload successfully');
console.log("From the upload route " + upload.getNewFileName()); // RETURNS UNDEFINED
});
module.exports = router;
Я надеваю не знаю, почему это возвращается неопределенным. Я передаю функцию. Я что-то пропустил?
Я также включил код uppy, который вам нужен.
uppy. js
// Import the plugins
const Uppy = require('@uppy/core');
const XHRUpload = require('@uppy/xhr-upload');
const Dashboard = require('@uppy/dashboard');
const uppy = Uppy({
debug: true,
autoProceed: false,
restrictions: {
maxFileSize: 1024000,
maxNumberOfFiles: 3,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', 'video/*']
}
})
.use(Dashboard, {
trigger: '.UppyModalOpenerBtn',
inline: true,
target: '#drag-drop-area',
replaceTargetContent: true,
showProgressDetails: true,
proudlyDisplayPoweredByUppy: false,
animateOpenClose: true,
note: 'Images and video only, 1–3 files, up to 1 MB',
height: 470,
browserBackButtonClose: true,
theme: 'dark',
metaFields: [
{id: 'caption', name: 'Caption', placeholder: 'describe what the image is about'}
]
});
uppy.on('file-added', (file) =>{
console.log(file);
uppy.setFileMeta(file.meta.id, {
caption: file.name
});
});
uppy.use(XHRUpload, {
id: 'XHRUpload',
endpoint: 'http://localhost:8000/upload',
method: 'POST',
formData: true,
fieldName: 'my_fieldName',
metaFields: ['caption'],
});
uppy.on('upload-success', (file, response) => {
console.log("File uploaded successfully ", file);
});
module.exports = uppy;
Если вам нужен другой код, дайте мне знать. Спасибо!
Кстати, я использую browserify для реализации Uppy. :)
Если Multer - не лучший способ загрузить файл на сервер с Uppy, я с радостью приму любую лучшую альтернативу. Спасибо!