Как получить доступ к парам имя / значение в объекте JSON из облачного хостинга изображений (React, Node, Ax ios, Cloudinary) - PullRequest
0 голосов
/ 07 апреля 2020

Я написал компонент реагирования, который пытается динамически отображать изображения, которые пользователь загружает при создании сообщения. Используя хостинг изображений cloudinary.com, я могу загрузить фотографию, используя созданный мной маршрут сервера. После загрузки cloudinary возвращает объект, который выглядит следующим образом:

received upload:
{
  public_id: 'prl3wpeo0ukaebhl3tdi',
  version: 1586274750,
  signature: '66fa908a6ba771cfc6776b94d82ff96cbbcaea37',
  width: 1200,
  height: 798,
  format: 'jpg',
  resource_type: 'image',
  created_at: '2020-04-07T15:52:30Z',
  tags: [],
  bytes: 206659,
  type: 'upload',
  etag: '350383f9f73de27461a78a6c550eb58a',
  placeholder: false,
  url: 
'http://res.cloudinary.com/countertable/image/upload/v1586274750/prl3wpeo0ukaebhl3tdi.jpg',
  secure_url: 'https://res.cloudinary.com/countertable/image/upload/v1586274750/prl3wpeo0ukaebhl3tdi.jpg', 
  original_filename: 'upload_3c8aa31fbfc7c6bd6ed2a5a96011fe73'
}

В ответ я пытаюсь получить имя / значение "public_id" и обновить свой компонент этим. Соответствующий код выглядит следующим образом:

// Функция, которая выполняет запрос get и сохраняет «public_id» как новое состояние для «thesis_img».

onUpload = () => {

    axios

      .get("http://localhost:8080/upload")
      .then((res) => {
        const thesis_img = res.data.public_id;
        console.log(res.data.public_id);
        this.setState({ thesis_img });
      })
      .catch((err) => console.log(err));
      console.log('help');
  };

// Соответствующая часть компонент реагирования, который создает сообщение с включенным изображением (в настоящее время есть кнопка проверки, которую я пытаюсь утешить. Записать имя / значение, чтобы доказать, что я его перехватил, фактически не создав целое сообщение.

<Modal.Header closeButton>
            <Modal.Title>Create Thesis</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <label htmlFor="thesis">Thesis</label>
            <input value={this.state.thesis} onChange={this.handleTextChange} />
            <label htmlFor="expiration_date">Expiration Date</label>
            <input
              type="date"
              value={this.state.antiThesisImg}
              onChange={this.handleDateChange}
            />
            <span className="text-danger">{this.state.error_message}</span>

            <form
              action="http://localhost:8080/upload"
              encType="multipart/form-data"
              method="post"
            >
              <label htmlFor="image-upload">Choose and Image</label>
              <input type="text" name="title" />
              <br />
              <input type="file" name="upload" multiple="multiple" />
              <br />
              <input type="submit" value="Upload"  />

            </form>
          </Modal.Body>
          <Modal.Footer>
          <Button variant="primary" onClick={this.onUpload}>
              Check
            </Button>
            <Button variant="primary" onClick={this.onSubmit}>
              Submit
            </Button>
          </Modal.Footer>

И, наконец, мой сервер для загрузки изображения:

http.createServer((req, res) => {
    if (req.url === '/upload' && req.method.toLowerCase() === 'post') {

        // parse a file upload
        const form = new Formidable();

        form.parse(req, (err, fields, files) => {

            //https://cloudinary.com/documentation/upload_images
            cloudinary.uploader.upload(files.upload.path, result => {

                console.log(result)
                if (result.public_id) {
                    res.writeHead(200, { 'content-type': 'text/plain' });
                    res.write('received upload:\n\n');
                    //app.put('http://localhost:3000/squabbles.Squabble.thesis_img', function (req, res) {
                    //    (result.public_id)

                    //});
                    console.log(result.public_id)
                    res.end(util.inspect(result));

                }


            }
            );
        });
        return;
    }

    // show a file upload form
//     res.writeHead(200, { 'content-type': 'text/html' });
//     res.end(`
//     <form action="/upload" enctype="multipart/form-data" method="post">
//       <input type="text" name="title" /><br/>
//       <input type="file" name="upload" multiple="multiple" /><br/>
//       <input type="submit" value="Upload" />
//     </form>
//   `);

}).listen(8080);

Я явно начинающий программист и потратил много часов, пытаясь сделать эту работу, но, к моему ужасу, я не могу получить приложение для регистрации "public_id". Любая помощь, указывающая мне в правильном направлении, будет с благодарностью.

Приветствия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...