I have successfully implemented file uploading in nodejs by two methods:
- uploaded a pdf using a HTML FileUploader and multer
- uploaded an Audio file using base64 string through a React Native Front end.
multer code:
app.use('/api/' + current_api_version + '/upload/ask-from-text', file_uploader.multi_upload('nf_uploader', 2), async (req, res) => {
response_helper.success(res, 200, { message: 'done', file_name: req.file_name }, 'done');
});
const multi_upload = (field_name_from_front_end, file_type) => {
// we need to inject the files uploaded by user
const storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log('destination', file);
cb(null, find_destination(req));
},
filename: function (req, file, cb) {
const file_obj = file_helper.break_file_name_with_extension(file.originalname);
const path = find_destination(req);
const uniqueSuffix = file_obj.file_name_wo_extension + '-' + Date.now() + '.' + file_obj.extension;
req.file_name = path + '/' + uniqueSuffix;;
console.log('this is expectedd :))', file);
cb(null, uniqueSuffix)
},
limits: {
fileSize: 1024 * 10240
}
});
return multer({ storage }).array(field_name_from_front_end, constants.UPLOAD.MAX_UPLOAD_FILES);
};
and File Saving base64:
app.use('/api/' + current_api_version + '/upload/ask-from-text', async (req, res) => {
console.log('json: ', Object.keys(req.body));
const fs = require('fs');
const copied = copy_to_clipboard(req.body.file_to_send.base64Str);
fs.writeFileSync('audio.mp4', Buffer.from(req.body.file_to_send.base64Str, 'base64'));
response_helper.success(res, 200, { message: 'done' }, 'done');
});
It is perfectly working fine, except, I couldn't use multer if I am not using any kind of uploader. I am unable to find what I missing here. My questions are:
When use HTML5 uploader, what exactly does it push to FormData which multer can easily read.
When I specifically created an object (not with the file uploader, but created object for an Audio file in my mobile) with file bytes and try to upload it through multer, it doesn't give any error, but it doesn't receive any files either. Sample object I sent:
const file_to_send = {
name: 'test_audio',
filename: 'test_audio.wav',
type: 'audio/x-wav',
size: '43719303',
uri: '/data/user/0/com.nfmobile/files/test_audio.wav',
file: bytes_from_the_file
};
const form_data = new FormData();
formData.append('nf_uploader', file_to_send)`
Now it doesn't give an error and neither does it say why it is not uploaded
That makes me wonder how does it actually work, can someone help me on how does it actually work? and What can be the problem? Am I missing the format of the object I should make so multer could understand or I am doing it the wrong way?
question from:
https://stackoverflow.com/questions/66061614/basic-info-about-file-upload-concepts 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…