Как загрузить изображение в облачное хранилище с помощью response и nodejs - PullRequest
0 голосов
/ 22 декабря 2018

Я пытаюсь загрузить изображение с помощью <input type="file" /> и загрузить это изображение для облачной обработки через маршрут узла.проблема в том, что файл никогда не попадает в бэкэнд.Когда я пытаюсь console.log(req.file), я получаю "неопределенный".

внешний интерфейс:

class AddPlayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      avatar: profilePicPlaceholder,
      avatarFile: "",
      name: "",
      age: "",
      apodo: "",
      captain: false,
      description: "",
      atributes: "",
      facebook: "",
      instagram: "",
      twitter: "",
      youtube: "",
      errors: {},
      displaySocialInputs: false
    };
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.onCheck = this.onCheck.bind(this);
    this.onImageChange = this.onImageChange.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }
  }

  onSubmit(e) {
    e.preventDefault();

    const playerData = {
      playerAvatar: this.state.avatarFile,
      name: this.state.name,
      age: this.state.age,
      apodo: this.state.apodo,
      captain: this.state.captain,
      description: this.state.description,
      atributes: this.state.atributes,
      facebook: this.state.facebook,
      instagram: this.state.instagram,
      twitter: this.state.twitter,
      youtube: this.state.youtube
    };

    this.props.addPlayer(playerData, this.props.history);
  }

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

  onImageChange(event) {
    //this is to see the picture in the page.
    if (event.target.files && event.target.files[0]) {
      this.setState({ avatarFile: event.target.files[0] });
      let reader = new FileReader();
      reader.onload = e => {
        this.setState({ avatar: e.target.result });
      };
      reader.readAsDataURL(event.target.files[0]);
    }
  }
  render() {
    <form
      onSubmit={this.onSubmit}
      method="post"
      encType="multipart/form-data"                
    >
     <div className="text-center mb-3">
                      <input
                        type="file"
                        name="file"
                        id="file"
                        accept="image/*"
                        className="inputfile"
                        onChange={this.onImageChange}
                      />
                      <label htmlFor="file" className="btn btn-primary">
                        Elegir foto
                      </label>
                    </div>
    </form>
  }
 }

AddPlayer.propTypes = {
  addPlayer: PropTypes.func.isRequired,
  profile: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  profile: state.profile,
  errors: state.errors
});

export default connect(
  mapStateToProps,
  { addPlayer }
)(withRouter(AddPlayer));

Это файл с маршрутом, который должен сохранить изображение в облачном виде:

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const passport = require("passport");
const fs = require("fs");
const multer = require("multer");
const cloudinary = require("cloudinary");
const cloudinaryStorage = require("multer-storage-cloudinary");

const cloudname = require("../../config/keys").cloudname;
const API_KEY = require("../../config/keys").API_KEY;
const API_SECRET = require("../../config/keys").API_SECRET;

cloudinary.config({
  cloud_name: cloudname,
  api_key: API_KEY,
  api_secret: API_SECRET
});

const storage = cloudinaryStorage({
  cloudinary: cloudinary,
  folder: "pics/",
  allowedFormats: ["jpg", "png"],
  transformation: [{ width: 500, height: 500, crop: "limit" }]
});

const parser = multer({ storage: storage });

router.post(
  "/player",
  [passport.authenticate("jwt", { session: false }), parser.single("file")],
  (req, res) => {
  console.log(req.file);
}
);

и server.js:

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");

const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const matches = require("./routes/api/matches");

const app = express();

//body-parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//db config
const db = require("./config/keys").mongoURI;

//connect to mongoose
mongoose
  .connect(
    db,
    { useNewUrlParser: true }
  )
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err));

//Passport middleware
app.use(passport.initialize());

//Passport config
require("./config/passport")(passport);


app.use("/api/profile", profile);

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`server running on port ${port}`));

Все данные, которые я отправляю, попадают на сервер, я могу обработать их с помощью req.body, но ничего в req.file.

Я надеюсь, что кто-то может мне помочь.Заранее спасибо.

...