Skip to content
Advertisement

React app not sending files to php server with Ajax

I’m hosting a react app on my apache server. I’m using react-images-upload npm package to receive an image from the user then post it to my php server with Axios.

However when I check the php $_FILES array in the response it’s empty.

I have tested wether my server can receive files with a little upload form on the php side, and it worked great, checked memory limits, that the folder on the server is writable and such. When I console.log(thumbnail) I get a file object in the console, so the uploader works

enter image description here

enter image description here

everything seems fine. So I suspect it’s something to do with the Ajax call.

Front end Code:

import React, { Component } from 'react'
import protocol from 'protocol.js';

import axios from 'axios';
import { Route, Switch, Redirect, useLocation } from "react-router-dom";

import styles from "components/Payment/Payment.module.css";
import "components/Payment/Payment.css";
import ImageUploader from 'react-images-upload';

var localStorage = require('local-storage');

class Payment extends Component {

  constructor(props) {
    super()

    this.state = {
      thumbnail: []
    }
    this.handlePayment = this.handlePayment.bind(this);
    this.onDrop = this.onDrop.bind(this);
  }

  onDrop(thumbnail) {
    this.setState({
        thumbnail: this.state.thumbnail.concat(thumbnail),
    });
  }  

  handlePayment() {
    var formData = new FormData();
    formData.append("thumbnail", this.state.thumbnail);
    
    axios.post('https://11.111.111.111/backend/ajax_controller.php', formData, {
      headers:{
       'Content-Type': 'multipart/form-data',
      },
    })
    .then(resp => {
      console.log(resp)
    })        
  }

  render() {

    return (
      <div className={styles.container}>

        <ImageUploader
            withPreview={true}
            singleImage={true}
            withIcon={true}
            buttonText='Profilna slika'
            onChange={this.onDrop}
            imgExtension={['.jpg', '.png']}
            maxFileSize={5242880}
            fileSizeError={"too big"}
        />

        <button className={styles.paymentButton} onClick={this.handlePayment}>Plati</button> 

      </div>
    )
  }
}

export default Payment;

Backend code:

print_r($_FILES);
if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], __DIR__."/assets/".$_FILES['thumbnail']['name'])) {            
 echo "done";
 } else {
  echo "error";
 }

Any help would be much appreciated.

Advertisement

Answer

I think this:

formData.append("thumbnail", this.state.thumbnail);

should be this:

formData.append("thumbnail", this.state.thumbnail[0]);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement