Warm tip: This article is reproduced from stackoverflow.com, please click
filepond java java-ee-8 reactjs servlets

Unable to visualize pdf file after submitting via FilePond component in React to a servlet(backend)

发布于 2020-08-15 08:57:37

I have a front React application with an upload document form via FilePond library and as backend I use Java to save the pdf document to my local files.

I am a little bit stucked beacause I have the pdf file and I can see the content(in Notepad/Code) but when I open it with Adobe/Microsoft Edge all pages are blank I don't know why.

In FilePond documentation it's not specified the defaut encoding and I don't know there is a way to see the encoding in the request(req).Also if it's not possible in this way how th send the file with getFileEncodeBase64String. Thank you very much for any ideas.

Code in React :

const APIClient = axios.create({
    // baseURL: 'https://postman-echo.com',
    baseURL: Config.faqServerUrl,      

    timeout: Config.timeout,            
    headers: {
        'Accept': 'application/json;charset=UTF-8',
        'Content-Type': 'application/json;charset=UTF-8'
    }
});

Call backend :

function processFile(fieldName, file, metadata, load, error, progress, abort, setFileName) {
    const formData = new FormData();
    let feedbackWS = null;
    formData.append('file', file, file.name);
   try{
    feedbackWS = APIClient.post('/upload-document',formData, {     
        onUploadProgress: (e) => {
            // updating progress indicator
            progress(e.lengthComputable, e.loaded, e.total);
        }
    }).then((response) => {
        load(response.data);
        setFileName(response.data);
      })
      .catch((error) => {
        console.error(error);
      });
    } catch (error) {
        console.log(error);
    }
}

FilePond component :

<FilePond
                       server={{
                            process:(fieldName, file, metadata, load, error, progress, abort) => {
                            processFile(fieldName, file, metadata, load, error, progress, abort);
                            } 
                        }}
                        oninit={() => handleInit()}

                        // callback onupdatefiles- a file has been added or removed, receives a list of file items
                         onupdatefiles={(fileItems) => {
                        // Set current file objects to this.state
                             setFile(fileItems.map(fileItem => fileItem.file));
                        }}
                        instantUpload={true}
                        onprocessfile={(error, file)=>{
                            console.log('PROCESSED', file, 'SERVER_ID', file.serverId);
                        //    console.log('ERROR PROCESSED', error);
                        }}

                        onaddfile={(error, file)=>{
                            console.log('PROCESSED', file, 'SERVER_ID', file.serverId);
                         //   console.log('ERROR PROCESSED', error);
                        }}
                    />

Java code :

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("encoding" + req.getCharacterEncoding()); // it is null

nom_upload_faq = "test.pdf";


            String repertoireFaqTemp = "/temp/"; 
            String pathComplet = repertoireFaqTemp + nom_upload_faq;

            File fichierTemp = null;
            try {

                fichierTemp = new File(pathComplet);

                if (fichierTemp.exists() && fichierTemp.isFile()) {
                    fichierTemp.delete();
                }

                if (fichierTemp.createNewFile()) {
                    fichierTemp.setReadable(true, false);
                    fichierTemp.setWritable(true, false);
                    fichierTemp.setExecutable(true, false);
                    fichierTemp.deleteOnExit();
                } else {
                    System.out.println("Impossible d'arriver ici on l'a déjà supprimer avant");
                }
            } catch (IOException e) {
                System.out.println("An error occurred.");
                e.printStackTrace();
            }
            //byte[] fileAsBytes = getArrayFromInputStream(req.getInputStream());
            byte[] fileAsBytes = null;
            try {
                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
                for (FileItem item: items) {
                    if(!item.isFormField()) {       // it'a file
                        fileAsBytes = getArrayFromInputStream(item.getInputStream());
                    }
                }
            } catch (FileUploadException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(fichierTemp))) {

                output.write(fileAsBytes);
                output.flush();
                output.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] getArrayFromInputStream(InputStream inputStream) throws IOException {
        byte[] bytes = null;
        byte[] buffer = new byte[1024];
        try (BufferedInputStream is = new BufferedInputStream(inputStream)) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int length;
            while ((length = is.read(buffer)) > -1) {
                bos.write(buffer, 0, length);
            }
            bos.flush();
            bytes = bos.toByteArray();
        } catch (Exception e) {
            System.out.println("toto");
        }
        return bytes;
    }

Req-body

Edit: Thank you Rik indeed the call formData.append('file', file, file.name); is the right one but still the same problem with the encoding(adding ? symbol) this is why I thought that it will be maybe the only possiblity to send the pdf file as base64 I've installed the plugin but as it'a asyncronous I can't call the methods getFileEncodeBase64String and in the servlet the request stream it's not the right one as you can see in the picture. Inital& after Request stream here you can see the sequence before the mouse selection I have an 8 with ?

Questioner
ana maria
Viewed
22
Rik 2020-05-28 15:16

You don't have to encode the file

formData.append('file', file.getFileEncodeBase64String(), file.name);

You can do:

formData.append('file', file, file.name);

And your browser will post a file object which you can handle like any other file posted with a form. See: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects