【问题标题】:How to upload a file to a Node Js Server如何将文件上传到 Node Js 服务器
【发布时间】: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 file html标签的name属性一样吗?
  • 它是image @VaibhavKumarGoyal

标签: android node.js file file-upload


【解决方案1】:
console.log('file.fieldname : ' + req.image.filename);

替换为

console.log(req);

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

【讨论】:

    【解决方案2】:

    首先,抱歉英语不好

    req.image 看起来未定义。

    我想,如果使用 Multer,就会有 req.file.image.filename

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

    此外,

    TypeError: 无法读取未定义的属性“文件名”

    这类错误在js中很容易找到。

    这些表示 foo.bar.undefined.filename

    只要找到它使用的地方。 (如果是文件名)

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 2017-04-25
      相关资源
      最近更新 更多