简体   繁体   English

如何从Android将文件上传到Node.js服务器

[英]How to upload a file to a Node.js server from Android

I am trying to upload a file to a Node.js server, but to no success. 我正在尝试将文件上传到Node.js服务器,但没有成功。

I keep getting the error TypeError: Cannot read property 'filename' of undefined on the Node side and I only get the onFailure called, and never the onSuccess . 我一直收到错误TypeError: Cannot read property 'filename' of undefined NodeTypeError: Cannot read property 'filename' of undefined并且我只调用了onFailure ,而从未调用过onSuccess

The following is what I have so far: 以下是我到目前为止的内容:

Java side 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;
}

Node side 节点侧

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);
})

Why am I getting fails with this. 为什么我为此失败。

Thank you all in advance. 谢谢大家。

NodeJS 节点JS

//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'));
        }
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM