使用react + nodejs上传图片

问题描述 投票:0回答:3

当我使用邮递员上传图像时,API 工作正常,并且图像被上传。但是当我尝试从前端(react)发送数据到后端(nodejs)时,这个错误不断发生:

无法读取未定义的属性“路径”

当我对上传图片的值进行

console.log()
时,我得到像这样的文件路径“C:akepath\moneyIcon.png”:

enter image description here

这是我的反应代码:

handleSubmit = (e) => {
e.preventDefault();
const data = new FormData();
data.append("file", this.state.Logo);
console.log(data);
console.log(`
    --SUBMITTING--
    First Name: ${this.state.firstName}
    Last Name: ${this.state.lastName}
    Email: ${this.state.email}
    Password: ${this.state.password}
    Logo:${this.state.Logo}
  `);
console.log(this.state.Logo);
const registered = {
  firstName: this.state.firstName,
  lastName: this.state.lastName,
  email: this.state.email,
  password: this.state.password,
  ConfirmPassword: this.state.ConfirmPassword,
  CompanyName: this.state.CompanyName,
  Website: this.state.Website,
  PhoneNumber: this.state.PhoneNumber,
  Adress: this.state.Adress,
  CompanyDescription: this.state.CompanyDescription,
  Logo: data,
};
axios
  .post("http://localhost:4000/app/company-registration", registered)
  .then((response) => {
    console.log(response.data);
    if (response.status == 200) {
      console.log("Successfully Registered");
      this.setState({
        firstName: "",
        lastName: "",
        email: "",
        password: "",
        date: "",
        error: "",
        Logo: "",
      });
    }
  })
  .catch((err) => {
    console.log(err);
    this.setState({
      error: "Company already exists",
    });
  });
};

onChangeHandler = (event) => {
this.setState({
  Logo: event.target.value,
});
};

<div className="firstName">
            <label htmlFor="Logo">Logo</label>
            <input
              type="file"
              className="campanyLogo"
              name="logo"
              accept=""
              onChange={this.onChangeHandler}
            />
          </div>

这是 Nodejs API:

router.post('/company-registration', upload.single('Logo'),async (request, response) => {
console.log(request.file)
let user = await Company.findOne({ email: request.body.email });
if (user) {
    return response.status(400).json('That company already exisits!');
} else {
    // Insert the new user if they do not exist yet
        companyuser = new Company({
        firstName:request.body.firstName,
        lastName:request.body.lastName,
        CompanyName: request.body.CompanyName,
        Website: request.body.Website,
        PhoneNumber: request.body.PhoneNumber,
        Adress: request.body.Adress,
        email:request.body.email,
        password:request.body.password,
        Logo: request.file.path,
        Sector: request.body.Sector,
    })
}
const saltPassword = await bcrypt.genSalt(10)
companyuser.password = await bcrypt.hash(request.body.password, saltPassword)

        await companyuser.save()
        .then(data => {
            response.json(data)
        })
        .catch(error => {
            response.json(error)
        })
            
    })
node.js reactjs express file-upload
3个回答
0
投票

发送图片的方式有很多种,但不能通过本地机器上的文件路径发送图片。我建议将其作为

byte array
发送,如果需要持久性,则将其发送到 blob storage 并跟踪数据库中的 url。


0
投票

您必须从文件事件而不是值中获取它。 改变这行代码

onChangeHandler = (event) => { this.setState({ Logo: event.target.files[0], });
祝你好运!


0
投票

我发现我的错误是我将徽标作为 formData 发送,将其他表单元素作为 application/json 发送,所以我将它们全部放入 formData 中,这修复了我的错误,谢谢你们的帮助!

const data = new FormData();
data.append("firstName", this.state.firstName);
data.append("lastName", this.state.lastName);
data.append("email", this.state.email);
data.append("password", this.state.password);
data.append("CompanyName", this.state.CompanyName);
data.append("Website", this.state.Website);
data.append("PhoneNumber", this.state.PhoneNumber);
data.append("Adress", this.state.Adress);
data.append("CompanyDescription", this.state.CompanyDescription);
data.append("Logo", this.state.Logo);
© www.soinside.com 2019 - 2024. All rights reserved.