Как загрузить файл на сервер Node Js

Я пытаюсь загрузить файл на сервер 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.info('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.info('file.fieldname : ' + req.image.filename)

    res.sendStatus(200);
})

Почему у меня с этим не получается.

Спасибо всем заранее.

upload.single('image') имя образа такое же, как свойство name вашего тега input type file html?

Vaibhav Kumar Goyal 26.12.2018 04:10

Это image @VaibhavKumarGoyal

Program-Me-Rev 26.12.2018 04:57
0
2
73
2

Ответы 2

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

заменить на

console.info(req);

И посмотрите, что у вас внутри запроса. Остановка узла выдает ошибку и должна возвращать 200.

Во-первых, извините за плохой английский

req.image выглядит неопределенным.

Думаю, если использовать Multer, будет req.file.image.filename

req.image => req.file.image // check req.file or req.files I confused.

КРОМЕ ТОГО,

TypeError: Cannot read property 'filename' of undefined

Ошибки такого типа очень легко найти в js.

These means foo.bar.undefined.filename

Просто найди где его использовали. (в случае имени файла)

Другие вопросы по теме