【发布时间】:2019-05-24 09:55:10
【问题描述】:
我正在尝试将文件上传到 Node.js 服务器,但没有成功。
我已经尝试了几天,我愿意接受任何事情;到目前为止我的方法的修复建议,甚至是一种完全不同的尝试方法。
使用我的代码,我在 Node 端不断收到错误 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)
res.sendStatus(200);
})
为什么我会失败。
提前谢谢大家。
【问题讨论】:
-
是
upload.single('image')的图片名称和你input type filehtml标签的name属性一样吗? -
它是
image@VaibhavKumarGoyal
标签: android node.js file file-upload