我正在尝试将文件上传到Node.js服务器,但是没有成功。
我在节点端不断收到错误TypeError: Cannot read property 'filename' of undefined
,而我只收到了onFailure
的电话,而从未收到onSuccess
的邮件。
以下是我到目前为止的内容:
Java方面
public void upload(final String filePath) {
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams requestParams = prepareRequestParams(filePath);
asyncHttpClient.post(LOCALHOST_FILE_UPLOAD_URL, requestParams, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody) {
Log.v("MyApp", "SUCCESS");
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
Log.v("MyApp", "FAIL");
}
});
}
private RequestParams prepareRequestParams(String filePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
RequestParams requestParams = new RequestParams();
try {
requestParams.put("image", inputStream, "image", new File(filePath).toURL().openConnection().getContentType());
} catch (IOException e) {
e.printStackTrace();
}
return requestParams;
}
节点端
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'rev_uploads/')
console.log('file.fieldname : ' + file.fieldname)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname))
}
})
var upload = multer({
storage: storage
})
app.use(express.static('public'));
app.post('/file_upload', upload.single('image'), function (req, res) {
console.log('file.fieldname : ' + req.image.filename)
//uploading.openIrfanView(__dirname, req.file.filename)
res.sendStatus(200);
})
为什么我失败了。
谢谢大家。
答案 0 :(得分:0)
NodeJS
//multers disk storage settings;
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './files/uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
}
}),
//multer settings
upload = multer({
storage: storage
}).single('file');
file.prototype.upload = function (req, res) {
console.log('=============================== Upload : Files ===============================');
let response = new Response();
upload(req, res, function (err) {
if (err) {
console.log('===== Files > Upload Error: ' + _util.inspect(err));
res.status(405).json(response.error(err, َ'Face to problem.'));
} else {
console.log('===== Files > Upload ok');
console.log(req.file.path);
res.status(200).json(response.success(req.file.path, 'Success'));
}
});
};