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,但页面仍然刷新。为什么会导致页面刷新,我该如何防止它?stopPropogationhandleChangephoto.write

4

1 回答 1

0

我通过将文件写入临时目录而不是静态文件夹来解决这个问题。页面重新加载由以下触发react-dev-utils/webpackHotDevClient.js

case 'content-changed':
  // Triggered when a file from `contentBase` changed.
  window.location.reload();
  break;

当我将文件写入../client/public/images/${Date.now()}.${extension}.

我确认使用上面的原始代码在生产版本中不存在该问题,但将其更改为以下代码,因此在开发过程中不会打扰我:

exports.uploadImage = async (req, res) => {
  if (!req.files) {
    return res.status(400).json({ msg: 'No file to upload' });
  }
  let file = req.files.file;
  const filePath = file.tempFilePath;
  const extension = file.mimetype.split('/')[1];
  file = await jimp.read(file.tempFilePath);
  await file.resize(370, jimp.AUTO).quality(75);
  await file.writeAsync(`${filePath}.${extension}`);
  cloudinary.uploader.upload(`${filePath}.${extension}`, function(err, result) { 
    if (err) {
      console.log('error', err);
    }
    res.json({ fileName: result.public_id });
  });
};
于 2020-07-20T12:56:41.570 回答