【问题标题】:How to Use Jimp to Resize Image for Upload without Refreshing in Node.js如何在 Node.js 中使用 Jimp 调整图像大小以进行上传而不刷新
【发布时间】:2020-11-05 15:24:19
【问题描述】:

在使用以下控制器上传到 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;

我在handleChange 上尝试了preventDefault 和stopPropogation,但页面仍然刷新。 为什么photo.write 会导致页面刷新,如何防止?

【问题讨论】:

    标签: javascript node.js jimp


    【解决方案1】:

    我通过将文件写入临时目录而不是静态文件夹来解决这个问题。页面重新加载由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 });
      });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 2021-08-15
      • 2019-01-25
      • 2015-04-02
      • 2017-03-25
      • 1970-01-01
      • 2014-07-24
      相关资源
      最近更新 更多