简体   繁体   中英

How to Use Jimp to Resize Image for Upload without Refreshing in Node.js

I'm trying to resize a file server-side using Jimp before uploading to Cloudinary in node.js with the following controller:

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 });
  });
};

This resizes the image and uploads it, but then the page refreshes, which I can't have. If I comment out await photo.write(filePath) the page does not refresh, but of course then the file uploaded is not resized.

The front end is React and looks something like this:

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;

I tried preventDefault and stopPropogation on handleChange but the page still refreshes. Why does photo.write cause the page to refresh and how can I prevent it?

I solved this by writing the file to a temp directory instead of the static files folder. The page reload is fired by react-dev-utils/webpackHotDevClient.js :

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

That is firing when I write the file to ../client/public/images/${Date.now()}.${extension} .

I confirmed the issue does not exist in a production build with the original code above, but changed it to the below so it wouldn't mess with me during dev:

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 });
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM