0

I am new to React JS The question is that I need to send my file in the form of react object array to php $_FILES, I am using axios .. thanks in advance

react code:

This is my react code:

<Row>
   <Col lg={4}>
     <FieldDetails>Upload your Category image here</FieldDetails>
   </Col>
   <Col lg={8}>
     <DrawerBox
       overrides={{
       Block: {
         style: {
           width: '100%',
           height: 'auto',
           padding: '30px',
           borderRadius: '3px',
           backgroundColor: '#ffffff',
           display: 'flex',
           alignItems: 'center',
           justifyContent: 'center',
         },
       },
     }}
    >
    <Uploader onChange={handleUploader} />
    </DrawerBox>
   </Col>
</Row>

This is handleuploader code-

 const handleUploader = files => {

console.log(files); }

This is my files array

lastModified: 1596798196975
lastModifiedDate: Fri Aug 07 2020 16:33:16 GMT+0530 (India Standard Time)
__proto__: Object
name: "8e8d3b5a5b132f26de41f7ec68c95bbb.jpg"
path: "8e8d3b5a5b132f26de41f7ec68c95bbb.jpg"
preview: "blob:http://localhost:3000/ee318d51-fa31-4173-ab08-2e728a26eca6"
size: 16578
type: "image/jpeg"

  • which library you using to upload files ? – DEEPAK Aug 25 '20 at 09:41
  • Does this answer your question? [How do I set multipart in axios with react?](https://stackoverflow.com/questions/41878838/how-do-i-set-multipart-in-axios-with-react) – goto Aug 25 '20 at 10:43

2 Answers2

0

Based on the names of your components, I assume that you want to upload files using ajax.

To upload files with ajax, you need to post FormData instead of JSON objects.

Here is the code:

const handleUploader = (file)=>{
    const fd = new FormData();
    fd.append('file', file);
    axios({
        method: 'POST',
        url: `https://url_to_backend`,
        data: fd,
        onUploadProgress: (progressEvent) => {
            const uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log("uploadProgress",uploadProgress);
        }
    }).then(res => {
        // after success
    }).catch(err => {
        // handle error
    })
}
mohsen saremi
  • 685
  • 8
  • 22
0

In case this code is intended for real world use (production) I would advise using a library to take care of the client-side file upload. There are many factors and edge-cases to handle for it to work cross-browser and in different scenarios.

Can recommend react-uploady. You can use the grouped prop to allow multiple files in the same request:

import React from "react";
import Uploady from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";

const App = () => (<Uploady 
    grouped
    destination={{ url: "https://my-server/upload" }}>
    <UploadButton/>
</Uploady>);
poeticGeek
  • 1,001
  • 10
  • 14