首页 > 解决方案 > 如何将文件上传到 Node Js 服务器

问题描述

我正在尝试将文件上传到 Node.js 服务器,但没有成功。

我已经尝试了几天,我愿意接受任何东西;到目前为止我的方法的修复建议,甚至是一种完全不同的尝试方法。

使用我的代码,我一直TypeError: Cannot read property 'filename' of undefinedNode端收到错误,我只得到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);
})

为什么我会失败。

谢谢大家。

标签: androidnode.jsfilefile-upload

解决方案


console.log('file.fieldname : ' + req.image.filename);

替换为

console.log(req);

看看你在查询里面有什么。节点停止抛出错误,必须返回 200。


推荐阅读