How to upload files using PrimeReact FileUpload Component
Asked Answered
P

1

5

I am a React/Spring beginner and I dont know how to make a Fileupload with Primereact. Their Documentation says following (https://www.primefaces.org/primereact/#/fileupload):

FileUpload requires a url property as the upload target and a name to identify the files at backend.

<FileUpload name="demo" url="./upload"></FileUpload>

But it neither say how do I fetch the data, how I access the "demo" in the backend, nor what kind of reponse I get.

Can anyone help me please? I have already searched the web but did not find anything.

Poussin answered 25/2, 2020 at 6:59 Comment(0)
A
8

You can do something like this:

<FileUpload name="invoice"
    accept="image/*"
    customUpload={true}
    uploadHandler={invoiceUploadHandler}
    mode="basic"
    auto={true}
    chooseLabel="Upload invoice"/>
const invoiceUploadHandler = ({files}) => {
    const [file] = files;
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
        uploadInvoice(e.target.result);
    };
    fileReader.readAsDataURL(file);
};

Send your request like this

const uploadInvoice = async (invoiceFile) => {
    let formData = new FormData();
    formData.append('invoiceFile', invoiceFile);

    const response = await fetch(`orders/${orderId}/uploadInvoiceFile`,
        {
            method: 'POST',
            body: formData
        },
    );
};

Important: Do not set any Content-Type header! This will be done automatically.

Aphorism answered 12/4, 2020 at 19:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.