Gérer l'upload d'une image

Comment ça marche côté React ?

import { Input } from 'reactstrap';

<Input
  value={values?.images}
  type="file"
  component="input"
  // multiple
  onChange={(event: any) => {
    const files = Array.from(event.target.files)
    const reader = new FileReader(); 
    reader.readAsDataURL(files[0] as Blob);
    reader.onload = function(upload: any) {
    setFieldValue('image', upload?.target?.result);
  };}}
/>

Le FormData

  handleUploadImage(ev) {
    ev.preventDefault();

    const data = new FormData();
    data.append('file', this.uploadInput.files[0]);
    data.append('filename', this.fileName.value);

    fetch('http://localhost:8000/upload', {
      method: 'POST',
      body: data,
    }).then((response) => {
      response.json().then((body) => {
        this.setState({ imageURL: `http://localhost:8000/${body.file}` });
      });
    });
  }

Comment ça marche côté NodeJS ?

const express = require('express');
const fileUpload = require('express-fileupload');

const app = express();

app.use(fileUpload());
app.use('/public', express.static(__dirname + '/public'));

app.post('/upload', (req, res, next) => {
  console.log(req);
  let imageFile = req.files.file;

  imageFile.mv(`${__dirname}/public/${req.body.filename}.jpg`, function(err) {
    if (err) {
      return res.status(500).send(err);
    }

    res.json({file: `public/${req.body.filename}.jpg`});
  });

})

app.listen(8000, () => {
  console.log('8000');
});

Gérer l'upload d'une image

By NicoHash

Gérer l'upload d'une image

  • 37