android - 如何将文件上传到 Node Js 服务器
问题描述
我正在尝试将文件上传到 Node.js 服务器,但没有成功。
我已经尝试了几天,我愿意接受任何东西;到目前为止我的方法的修复建议,甚至是一种完全不同的尝试方法。
使用我的代码,我一直TypeError: Cannot read property 'filename' of undefined
在Node端收到错误,我只得到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);
})
为什么我会失败。
谢谢大家。
解决方案
console.log('file.fieldname : ' + req.image.filename);
替换为
console.log(req);
看看你在查询里面有什么。节点停止抛出错误,必须返回 200。
推荐阅读
- javascript - 如何更新 index.html 文件中的 javascript?
- artifactory - Artifactory cli - 下载现有文件
- azure - 在 azure 活动目录中使用相同的用户 ID 限制多个用户登录
- android - 世博推送通知未在 Android 手机中弹出(浮动通知)
- .net - 同一计算引擎上的多个 Web 应用程序
- android - 如何在 volley、android 中使用 GET 方法向后端发送参数并获取响应消息?
- python - 分而治之的数组求和还是基于循环的数组求和?
- javascript - 解释数组 - 连接到特定对象
- python - Flask-appbuilder 上的路由 - 构建错误
- c# - 如何从其他场景加载精灵?