Source:  Twitter logo

I have been searching for a while for a ReactJS component to allow you to upload a file from a browser and have it saved to the server ReactJS is running on.

I have found various components for drag and drop etc and superagent for possibly saving the file to the server but I figured someone might have created a component for all of this?

The back end is a Java application using Spring Boot, Spring Data JPA and Spring Data REST.

Does anyone know of one or a tutorial on setting up a basic way to save the file to the server?

Solution

In the end I used part of the solution below with dropzone and superagent and then utilized the Spring guide (https://spring.io/guides/gs/uploading-files/)

Uploader component

'use strict';

const React = require('react');
const ReactDOM = require('react-dom');

const log = require('./log'); // logger to enable debug alerts

// import the components
const Dropzone = require('react-dropzone');
const request = require('superagent');

//'application/java-archive'
class Uploader extends React.Component {
  constructor(props) {
    super(props);
    this.dropHandler = this.dropHandler.bind(this);
  }

  dropHandler(file) {
    var jsonFile = new FormData();
    jsonFile.append('file', file[0]);
    jsonFile.append('name', file[0].name);

    request.post('/upload')
    .send(jsonFile)
    .end(function(err, resp) {
      if (err) {
        console.error(err);
      }
      return resp;
    });
  }


  render() {
    return (
      <Dropzone disableClick={false} multiple={false} accept={'application/java-archive'} onDrop={this.dropHandler}>
        < div > Drop a Appium Jar, or click to add. < /div >
      </Dropzone>
    );
  }
}

module.exports = Uploader

FileUploadController

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody ResponseEntity<String>  handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file) throws Exception{
        if (name.contains("/")) {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Folder separators not allowed.");
        } else if (name.contains("/")) {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Relative pathnames not allowed.");
        } else if (!name.endsWith(".jar")) {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("File type not allowed.  Must be a Jar file type ending in '.jar'.");
        }

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return ResponseEntity.ok("File " + name + " uploaded.");
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(e.getMessage());
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("You failed to upload " + name + " because the file was empty.");
        }
    }
}

You would want to do this through your server. What kind of backend are you using? If you are using Node.js there is an npm module called Multer that saves files to your server. I talk about it some in my blogpost about react dropzones. Without more info on your backend its hard to say exactly what you need to do.

2 users liked answer #0dislike answer #02
Rico Rojas profile pic
Rico Rojas

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).