How to upload a file (image). req.files is always undefined
I am trying to upload an image but the content of request.files is always undefined. What I am doing wrong?
Server
import restify = require('restify');
var api = restify.createServer();
restify.CORS.ALLOW_HEADERS.push('authorization');
api.use(restify.CORS());
api.pre(restify.pre.sanitizePath());
api.use(restify.acceptParser(api.acceptable));
api.use(restify.bodyParser());
api.use(restify.queryParser());
api.use(restify.authorizationParser());
api.use(restify.fullResponse());
api.post('/images', (req, res, next) => {
console.log('UPLOADED FILES: ', req.files);
res.json(200);
return next();
});
Client
var fs = require("fs");
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:1337/images',
headers:
{ 'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
formData:
{ avatar:
{ value: 'fs.createReadStream("one")',
options: { filename: 'one', contentType: null } } } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Hey @sulhome, what version of restify are you using? import restify = require('restify') doesn't seem to be valid, and restify.CORS has been removed and moved to https://github.com/TabDigital/restify-cors-middleware/ in the 5.x release
@retrohacker I am using version 4
import restify = require('restify') is TypeScript syntax
Hi, I'm using restify for file uploads only, my application will go live next month. but I'm not using restify itself for handling multipart request. i'm using busboy beside this. like below ...
simpleUpload(req, inputOptions) {
let options = this._generateConfiguration(inputOptions);
return new Promise((resolve, reject) => {
if (!options.uploadPath || options.uploadPath === '') {
reject({errorCode: 'sc01'});
}
let busboy = new Busboy({ headers: req.headers, limits: options.limits });
let actionBody = [];
let numberOfFiles = 0;
/**
* since busboy event firing is not in a proper sequence and it's buggy, I'm using this trick to call resolve after all files parsed
*/
function sendResolutionResponse() {
if (numberOfFiles > 0) {
setTimeout(function() {
sendResolutionResponse();
}, 250);
} else {
resolve(actionBody);
}
}
busboy.on('file', function(fieldName, file, filename, encoding, mimetype) {
logger.log('File Received - FN: ',fieldName, ', FN: ',filename, encoding, mimetype);
numberOfFiles++;
let brokenStream = false;
let fileSize = 0;
let FileName = null;
// start saving the file
FM.saveFile(options.uploadPath + filename).then(savedFile => {
FileName = savedFile.split('/');
FileName = FileName[FileName.length -1];
file.pipe(fs.createWriteStream(savedFile));
file.on('data', function(data) {
fileSize += data.length;
});
file.on('limit', function() {
// do something
});
file.on('end', function() {
// do something
});
file.on('error', function(error) {
// todo: error handling should be implemented, issue number #7
logger.error('Error happened due parsing the file', error);
});
});
});
busboy.on('filesLimit', function () {
logger.log('Files Number Limit has been reached.');
sendResolutionResponse();
});
busboy.on('finish', function() {
logger.log('Parsing Form Finished');
sendResolutionResponse();
});
req.pipe(busboy);
});
}
I just copy&paste this code from my application part, it's not clean but the structure is good and it's working, and its very fast. you can modify it, but before that you need to know how busboy is working for better understanding
Thank you for chiming in to help @ehsanagh ! Hope this resolved your problem @sulhome, if not please comment and we can re-open.