【问题标题】:Multer with node.js / react-native not working使用 node.js / react-native 的 Multer 不起作用
【发布时间】:2021-12-10 08:27:56
【问题描述】:

我正在使用 react-native 创建一个应用程序,我正在使用图像选择器选择图像并单击按钮以创建将图像发送到 node.js 服务器的部分。

但是,在上传图片的过程中,其他附加信息一般都保存在mysql中,而图片不保存在upload文件夹中。

Multer 版本 1.4.2。 Node.js 版本 16.12.0

在 react-native 代码中(数据到 node.js)

onPress={() => {
                  if (this.state.image === null) {
                    alert("이미지를 넣어주세요");
                  } else {
                    Alert.alert(
                      "구인 공고를 등록할까요?",
                      "등록후, 수정할 수 없으니 꼼꼼히 확인 부탁~!!",
                      [
                        {
                          text: "Cancel",
                          onPress: () => alert("취소하였습니다."),
                          style: "cancel"
                        },
                        {
                          text: "OK",
                          onPress: async () => {
                            const formData = new FormData();
                            formData.append("db_title", this.state.title);
                            formData.append("db_wtype", this.state.type);
                            formData.append("db_sdate", this.state.start);
                            formData.append("db_edate", this.state.end);
                            formData.append("db_money", this.state.money);
                            formData.append(
                              "db_address",
                              this.state.address
                            );
                            formData.append(
                              "db_description",
                              this.state.addition
                            );
                            formData.append("file", this.state.image);
                            formData.append("db_stime", "9");
                            formData.append("db_etime", "18");
                            formData.append("db_smin", "00");
                            formData.append("db_emin", "30");
                            await AsyncStorage.getItem("pubKey").then(
                              (pubKey) => {
                                formData.append("db_pubkey", pubKey);
                              }
                            );

                            const {
                              data: { result }
                            } = await axios.post(
                              "http://127.0.0.1:4000/upload",
                              formData
                            );
                            console.log(result);
                            alert(result);
                            this.props.navigation.navigate("Announce");
                          }
                        }
                      ],
                      { cancelable: false }
                    );
                  }
                }}

在我的节点服务器代码中

const multer = require('multer');

const _storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, '/upload')
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now())
    }
  })
const upload = multer({ storage: _storage });

router.post("/", upload.single("file"), function (req, res) {

  console.log(req.body);
  console.log(req.body.file);

  Article.create({
    db_title: req.body.db_title,
    db_wtype: req.body.db_wtype,

    db_sdate: req.body.db_sdate,
    db_edate: req.body.db_edate,

    db_stime: req.body.db_stime,
    db_etime: req.body.db_etime,

    db_smin: req.body.db_smin,
    db_emin: req.body.db_emin,

    db_pubkey: req.body.db_pubkey,

    db_money: req.body.db_money,
    db_address: req.body.db_address,
    db_description: req.body.db_description,
    db_img: req.body.file
  })
    .then(result => {
      console.log("result : " + result);
      res.status(201).json({ result: "공고가 등록 되었습니다." });
    })
    .catch(err => {
      console.error("err : " + err);
    });
 });

 module.exports = router;

这是 node.js 控制台日志

  • 编辑图像选择器 (this.state.image)
    _pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3]
    });

    console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ");
    console.log(
      result
    );
    console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ");
    if (!result.cancelled) {
      this.setState({ image: result.uri });
    }
  };

【问题讨论】:

  • 我无法使用您提供的代码重现错误。请确保您拥有Minimal Reproducible Example...
  • @LinusUnnebäck 更新我的帖子!请查收~
  • 似乎this.state.image 包含文件的网址,但我无法确定,因为您没有包含设置它的代码...
  • @LinusUnnebäck 我忘记了,抱歉我又编辑了我的帖子!
  • 您只是将 uri 作为字符串存储到图像中 this.setState({ image: result.uri })。所以这只会将字符串"file:///example.jpg" 发送到您的服务器而不是文件。我不熟悉 FormData 在 React Native 上的工作方式,但这可能会对您有所帮助:dev.to/naderalfakesh/uploading-files-in-react-native-470m

标签: node.js react-native express axios multer


【解决方案1】:

你需要使用multer制作的路径:

改变:

db_img: req.body.file

db_img: req.file.path

【讨论】:

  • 我改变了这样的路径,但服务器返回请求失败代码 500。
  • 尝试查看req 实际包含的内容。 multer 是否填充了req.file?您可以在其他两个控制台语句之后添加console.dir(req.file)
  • 它返回未定义但console.dir(req.body.file)return 文件位置
  • 看起来 multer 中间件没有被以某种方式使用——通常情况下应该相反——req.body.fileundefined,而req.file 是一个由 multer 填充的对象。您可以向 destinationfile 函数添加一些日志记录,以查看它们是否运行。
猜你喜欢
  • 2021-10-17
  • 2015-03-09
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
相关资源
最近更新 更多