-1

create async thunk: enter image description here this is my node js api route router.post('/', upload.single('image'), protect, setAd)

this is my react js code export const sellBike = (bikeData) => API.post("/", bikeData);

my react js api const API = axios.create({baseURL:"http://localhost:8000"});

2 Answers2

1

Generally for uploading a photo on the nodejs they use multer package. You can see all details on its document. Also, you should set multipart/form-data on request's header. Here is the link

I guess you can upload a photo on backend after you read those links

Halil
  • 211
  • 2
  • 7
0

example from my project:

  1. convert img to string

img.toDataURL()

  1. Post to backend

const saveAvatar = () => axios.post<string[]>(http://${DOMAIN}/profile/saveAvatar/${id}, { avatar } );

  1. Take and save

    profile.post('/saveAvatar/:id', async (req, res) => { try { const { id } = req.params; const { avatar } = req.body; const data = avatar.replace(/^data:image/\w+;base64,/, ""); const buf = Buffer.from(data, 'base64');

    const login = await pool.query(
      "SELECT login FROM accounts WHERE id = $1", [id]
    );
    
    fs.writeFile(`${userImgPath}/app_data/images/users/${login.rows[0].login}.png`,
    

    buf, (err) => { if (err) throw err; console.log('The file has been saved!'); }); } catch (err: any) { console.error(err.message); } });

Gibloor
  • 143
  • 6
  • yeah, i converted image data to string and passed to api post request with header and authorization it works !! .. previously it was giving me error because i have implemented base 64 in front end and my backend accepts only binary image – DhunganaSushant Sep 11 '22 at 05:43