2

次のコントローラーを使用して node.js で Cloudinary にアップロードする前に、Jimp を使用してサーバー側でファイルのサイズを変更しようとしています。

exports.uploadImage = async (req, res) => {
  if (!req.files) {
    return res.status(400).json({ msg: 'No file to upload' });
  }
  const file = req.files.file;
  const extension = file.mimetype.split('/')[1];
  const filePath = `../client/public/images/${Date.now()}.${extension}`;
  const photo = await jimp.read(file.tempFilePath);
  await photo.resize(600, jimp.AUTO);
  await photo.write(filePath);
  cloudinary.uploader.upload(filePath, function(err, result) { 
    if (err) {
      console.log('error', err);
    }
    res.json({ fileName: result.public_id });
  });
};

これにより、画像のサイズが変更されてアップロードされますが、ページが更新されますが、これはできません。コメントアウトするawait photo.write(filePath)と、ページは更新されませんが、もちろん、アップロードされたファイルのサイズは変更されません。

フロントエンドは React で、次のようになります。

import React from 'react';
import axios from 'axios';

  handleChange = async (event) => {
    const formData = new FormData(); 

    formData.append('file', event.target.files[0]);

    const res = await axios.post('http://localhost:8000/api/uploadImage', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    this.imageRef.current.setAttribute('data-path', `${res.data.fileName}`);
  }

  render() {
    return (
      <form onSubmit={this.formSubmit}>
        <div>
          <label htmlFor='file-input'>
            <img />
          </label>
          <input name="image" id='file-input' type="file" accept="image/png, image/jpeg" data-path="" ref={this.imageRef} onChange={this.handleChange} />
        </div>
      </form>
    );
  }
}

export default AddItemForm;

試しpreventDefaultてみstopPropogationましhandleChangeたが、ページはまだ更新されます。によってページが更新されるのはなぜphoto.writeですか? また、それを防ぐにはどうすればよいですか?

4

1 に答える 1